How do I test GraphQL resolvers with graphql-go in Go?

Testing GraphQL resolvers in Go can be effectively achieved using the graphql-go library. The following example demonstrates how to set up a simple GraphQL server and test its resolvers using the Go testing framework.

// Import necessary packages import ( "context" "net/http" "net/http/httptest" "testing" "github.com/graphql-go/graphql" "github.com/graphql-go/handler" ) // Define your GraphQL schema var schema, _ = graphql.NewSchema(graphql.SchemaConfig{ Query: graphql.NewObject(graphql.ObjectConfig{ Name: "Query", Fields: graphql.Fields{ "hello": &graphql.Field{ Type: graphql.String, Resolve: func(p graphql.ResolveParams) (interface{}, error) { return "Hello, world!", nil }, }, }, }), }) // Set up a GraphQL handler var h = handler.New(&handler.Config{ Schema: &schema, GraphiQL: true, }) // Create a test server func testServer() *httptest.Server { return httptest.NewServer(h) } // Test the GraphQL resolver func TestHelloResolver(t *testing.T) { server := testServer() defer server.Close() resp, err := http.Post(server.URL, "application/json", strings.NewReader(`{"query": "{ hello }"}`)) if err != nil { t.Fatalf("Failed to make request: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { t.Fatalf("Expected status OK, got %v", resp.Status) } // Further response validation logic can go here }

GraphQL Go graphql-go resolvers testing Go testing framework