我想在 go 中为 GraphQL api (gqlgen) 编写单元测试(我检查了 GraphQL 操场中的功能并且一切正常)
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
}
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 中按下运行测试时,它会输出一长串错误。我认为问题可能出在我在测试中定义 GraphQL 客户端的方式上,但我不确定。我是 GraphQL 的新手,一般情况下,如果有任何帮助/建议,我将不胜感激。谢谢