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 (将#修改为@)