在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中文網其他相關文章!