首頁  >  文章  >  後端開發  >  使用 STRETCHR/TESTIFY 和 MOCKERY 進行 GOL 測試

使用 STRETCHR/TESTIFY 和 MOCKERY 進行 GOL 測試

Linda Hamilton
Linda Hamilton原創
2024-10-16 22:08:29661瀏覽

GOLANG TESTING WITH STRETCHR/TESTIFY AND MOCKERY

讓我們來看一個全面的範例,其中涵蓋了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

程式碼概述

  1. user_client.go

    該文件定義了與外部使用者 API 互動的介面。

    package project
    
    type User struct {
        ID   int
        Name string
    }
    
    type UserClient interface {
        GetUserByID(id int) (*User, error)
    }
    
  2. 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
    }
    
  3. 使用嘲諷產生模擬

    您可以使用 mockery 為 UserClient 產生模擬:

    mockery --name=UserClient --output=./mocks
    

    這將在mocks/UserClient.go 中產生一個模擬。

  4. 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)
        }
    
    

本例的要點

  1. 帶有的斷言證明:
    • assert 和 require 套件用於不同類型的檢查。
    • require 用於檢查如果失敗則應立即使測試失敗(例如,檢查 nil 錯誤)。
    • 斷言用於即使失敗也可以繼續的檢查(例如,比較值)。
  2. 嘲笑來嘲笑:
    • mockery 產生 UserClient 介面的模擬。
    • 在測試中,模擬配置為 .On() 來指定預期輸入,並使用 .Return() 來指定輸出。
    • AssertExpectations 驗證是否使用預期輸入呼叫了模擬方法。
  3. 測試錯誤處理
    • 一個測試檢查成功場景,而另一個測試則測試服務如何處理來自 UserClient 的錯誤。

此設定涵蓋了stretcher/testify 的斷言和模擬的基本功能,為 Golang 中的單元測試提供了結構化且可維護的方法。

以上是使用 STRETCHR/TESTIFY 和 MOCKERY 進行 GOL 測試的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn