讓我們來看一個全面的範例,其中涵蓋了stretchr/testify函式庫的常見功能以及Golang中的mockery。此範例將包括使用斷言進行測試、使用 require 套件進行嚴格斷言、測試 HTTP 處理程序以及使用 mockery 模擬依賴項。
假設我們有一個從外部 API 取得使用者資訊的服務。我們想要測試:
/project │ ├── main.go ├── service.go ├── service_test.go ├── user_client.go ├── mocks/ │ └── UserClient.go (generated by mockery) └── go.mod
user_client.go
該文件定義了與外部使用者 API 互動的介面。
package project type User struct { ID int Name string } type UserClient interface { GetUserByID(id int) (*User, error) }
service.go
該檔案包含一個使用 UserClient 取得使用者詳細資訊的服務。
package project import "fmt" type UserService struct { client UserClient } func NewUserService(client UserClient) *UserService { return &UserService{client: client} } func (s *UserService) GetUserDetails(id int) (string, error) { user, err := s.client.GetUserByID(id) if err != nil { return "", fmt.Errorf("failed to get user: %w", err) } return fmt.Sprintf("User: %s (ID: %d)", user.Name, user.ID), nil }
使用嘲諷產生模擬
您可以使用 mockery 為 UserClient 產生模擬:
mockery --name=UserClient --output=./mocks
這將在mocks/UserClient.go 中產生一個模擬。
service_test.go
現在,讓我們使用 testify 斷言和模擬生成的模擬為 UserService 編寫一個測試。
package project_test import ( "errors" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/mock" "project" "project/mocks" ) func TestUserService_GetUserDetails_Success(t *testing.T) { // Create a new mock client mockClient := new(mocks.UserClient) // Define what the mock should return when `GetUserByID` is called mockClient.On("GetUserByID", 1).Return(&project.User{ ID: 1, Name: "John Doe", }, nil) // Create the UserService with the mock client service := project.NewUserService(mockClient) // Test the GetUserDetails method result, err := service.GetUserDetails(1) // Use `require` for error checks require.NoError(t, err) require.NotEmpty(t, result) // Use `assert` for value checks assert.Equal(t, "User: John Doe (ID: 1)", result) // Ensure that the `GetUserByID` method was called exactly once mockClient.AssertExpectations(t) } func TestUserService_GetUserDetails_Error(t *testing.T) { // Create a new mock client mockClient := new(mocks.UserClient) // Define what the mock should return when `GetUserByID` is called with an error mockClient.On("GetUserByID", 2).Return(nil, errors.New("user not found")) // Create the UserService with the mock client service := project.NewUserService(mockClient) // Test the GetUserDetails method result, err := service.GetUserDetails(2) // Use `require` for error checks require.Error(t, err) assert.Contains(t, err.Error(), "user not found") // Ensure that the result is empty assert.Empty(t, result) // Ensure that the `GetUserByID` method was called exactly once mockClient.AssertExpectations(t) }
此設定涵蓋了stretcher/testify 的斷言和模擬的基本功能,為 Golang 中的單元測試提供了結構化且可維護的方法。
以上是使用 STRETCHR/TESTIFY 和 MOCKERY 進行 GOL 測試的詳細內容。更多資訊請關注PHP中文網其他相關文章!