微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

GraphQL 解析器的单元测试

如何解决GraphQL 解析器的单元测试

我想在 go 中为 GraphQL api (gqlgen) 编写单元测试(我检查了 GraphQL playground 中的功能,一切正常) 架构

type Farmer {
    id: Int!
    name: String!
    surname: String!
    dob: Date!
    fin: String!
    plot_loc_lat: String!
    plot_loc_long: String!
    createdAt: Time!
    updatedAt: Time!
    createdBy: String!
    updatedBy: String!
}

input NewFarmer {
    name: String!
    surname: String!
    dob: Date!
    fin: String!
    plot_loc_lat: String!
    plot_loc_long: String!
}

type Mutation {
    createFarmer(input: NewFarmer!): Farmer!
}

创建解析器

func (r *mutationResolver) CreateFarmer(ctx context.Context,input model.NewFarmer) (*model.Farmer,error) {
    //Extract the logged in user's role from the context (prevIoUsly set up by the middleware)
    Role,_ := ctx.Value("role").(string)

    //Check if the user has proper permissions to perform the operation
    if !utils.Contains([]string{"System Admin","Farmer"},Role) {
        return nil,errors.New("You are not authorized to access this entity")
    }

    //Establish connection to the database
    db := model.FetchConnection()

    //Defer closing
    defer db.Close()

    //Extract user ID from the context (prevIoUsly set up by the middleware)
    //Pass it to CreatedBy,UpdatedBy fields
    UID,_ := ctx.Value("user_id").(string)

    //Create a new instance in the table
    farmer := model.Farmer{Name: input.Name,Surname: input.Surname,dob: input.dob,Fin: input.Fin,PlotLocLat: input.PlotLocLat,PlotLocLong: input.PlotLocLong,CreatedAt: time.Now(),UpdatedAt: time.Now(),CreatedBy: UID,UpdatedBy: UID}
    db.Create(&farmer)
    return &farmer,nil
}

我尝试编写一个测试函数(遵循这些 two sources

func TestFarmers(t *testing.T) {

    c := client.New(handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{})))

    t.Run("Create a farmer",func(t *testing.T) {
        q := `
        mutation {
            createFarmer(input:{name:"Lee",surname:"Mack",dob:"20-May-1968",fin:"1234",plot_loc_lat:"40.8787",plot_loc_long:"89.3454"}){
                id,name,surname,dob,fin,plot_loc_lat,plot_loc_long,createdAt,updatedAt,createdBy,updatedBy
            }
        }
        `
        var farmer model.Farmer

        c.MustPost(q,&farmer)

        require.Equal(t,"Lee",farmer.Name)
        require.Equal(t,"Mack",farmer.Surname)
    })

}

当我在 VS Code 中按下 run test 时,它会输出一长串错误。我认为问题可能出在我在测试中定义 GraphQL 客户端的方式上,但我不确定。我是 GraphQL 的新手并且一般情况下,并希望得到任何帮助/建议。谢谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。