在 Golang 应用程序中测试 GraphQL 查询和突变时,拥有强大的测试策略至关重要,以确保您的应用程序的功能和可靠性API 端点。
坐落在迷宫般的 Golang 测试框架中,testify 因其简单性和全面性而成为首选。结合 gqlgen/client 包(它为测试 GraphQL 提供了宝贵的帮助),您可以深入研究有效单元测试的回报领域。
让我们开始一个实际示例来说明测试 GraphQL 查询和突变的过程:
<code class="go">// graph/resolver/root.resolver_test.go import ( "context" "testing" "github.com/99designs/gqlgen/client" "github.com/99designs/gqlgen/graphql/handler" "github.com/mrdulin/gqlgen-cnode/graph/generated" "github.com/mrdulin/gqlgen-cnode/graph/model" "github.com/mrdulin/gqlgen-cnode/mocks" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) ... type MockedUserService struct { mock.Mock } func (s *MockedUserService) GetUserByLoginname(loginname string) *model.UserDetail { args := s.Called(loginname) return args.Get(0).(*model.UserDetail) } func (s *MockedUserService) ValidateAccessToken(accesstoken string) *model.UserEntity { args := s.Called(accesstoken) return args.Get(0).(*model.UserEntity) } ...</code>
利用这些模拟对象,我们可以继续制作全面的单元测试来验证 GraphQL 解析器的功能:
<code class="go">// graph/resolver/root.resolver_test.go ... // TestMutationResolver_ValidateAccessToken is a test example for the ValidateAccessToken mutation. func TestMutationResolver_ValidateAccessToken(t *testing.T) { t.Run("should validate accesstoken correctly", func(t *testing.T) { // Create a mocked user service mockedUserService := new(mocks.MockedUserService) // Inject the mocked service into our resolver resolvers := resolver.Resolver{UserService: mockedUserService} // Create a GraphQL client c := client.New(handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &resolvers}))) // Set up expected return values from the mock service ue := model.UserEntity{ID: "123", User: model.User{Loginname: &loginname, AvatarURL: &avatarURL}} mockedUserService.On("ValidateAccessToken", mock.AnythingOfType("string")).Return(&ue) // Run the GraphQL mutation query var resp struct { ValidateAccessToken struct{ ID, Loginname, AvatarUrl string } } q := ` mutation { validateAccessToken(accesstoken: "abc") { id, loginname, avatarUrl } } ` c.MustPost(q, &resp) // Assert that the mock service was called as expected mockedUserService.AssertExpectations(t) // Check the response from the GraphQL mutation require.Equal(t, "123", resp.ValidateAccessToken.ID) require.Equal(t, "mrdulin", resp.ValidateAccessToken.Loginname) require.Equal(t, "avatar.jpg", resp.ValidateAccessToken.AvatarUrl) }) } ...</code>
通过实施这种测试方法,您可以有效地仔细检查您的 GraphQL 解析器,并为您的应用程序奠定质量和可靠性的坚实基础。
以上是如何在 Golang 中使用 Testify 和 GQLgen 有效测试 GraphQL 查询和突变?的详细内容。更多信息请关注PHP中文网其他相关文章!