GraphQL 및 Go로 작업할 때 단위 테스트는 코드의 정확성과 신뢰성을 보장하는 데 매우 중요합니다. 다음은 언급한 프레임워크를 고려하여 Go를 사용하여 GraphQL 쿼리 및 변형을 효과적으로 단위 테스트하는 방법을 보여주는 간단한 예입니다.
<code class="go">package resolver_test import ( "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/graph/resolver" "github.com/mrdulin/gqlgen-cnode/mocks" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) // Define mock objects for UserService 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) } // Test MutationResolver_ValidateAccessToken func TestMutationResolver_ValidateAccessToken(t *testing.T) { t.Run("should validate accesstoken correctly", func(t *testing.T) { // Create a mock UserService testUserService := new(mocks.MockedUserService) resolvers := resolver.Resolver{UserService: testUserService} // Create a GraphQL client c := client.New(handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &resolvers}))) // Define the expected user entity ue := model.UserEntity{ID: "123", User: model.User{Loginname: &loginname, AvatarURL: &avatarURL}} // Set the mock UserService to return the expected user entity testUserService.On("ValidateAccessToken", "abc").Return(&ue) // Define the query to test var resp struct { ValidateAccessToken struct{ ID, Loginname, AvatarUrl string } } q := ` mutation { validateAccessToken(accesstoken: "abc") { id, loginname, avatarUrl } } ` // Execute the query and assert the results c.MustPost(q, &resp) testUserService.AssertExpectations(t) require.Equal(t, "123", resp.ValidateAccessToken.ID) require.Equal(t, loginname, resp.ValidateAccessToken.Loginname) require.Equal(t, avatarURL, resp.ValidateAccessToken.AvatarUrl) }) } // Test QueryResolver_User func TestQueryResolver_User(t *testing.T) { t.Run("should query user correctly", func(t *testing.T) { // Create a mock UserService testUserService := new(mocks.MockedUserService) resolvers := resolver.Resolver{UserService: testUserService} // Create a GraphQL client c := client.New(handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &resolvers}))) // Define the expected user detail u := model.UserDetail{User: model.User{Loginname: &loginname, AvatarURL: &avatarURL}, Score: &score, CreateAt: &createAt} </code>
위 내용은 Go에서 gqgen을 사용하여 GraphQL 쿼리 및 돌연변이를 단위 테스트하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!