首頁  >  文章  >  後端開發  >  斷言:模擬:我不知道要回傳什麼,因為方法呼叫是意外的 在 Go 中編寫單元測試時出錯

斷言:模擬:我不知道要回傳什麼,因為方法呼叫是意外的 在 Go 中編寫單元測試時出錯

王林
王林轉載
2024-02-10 09:00:18494瀏覽

断言:模拟:我不知道要返回什么,因为方法调用是意外的 在 Go 中编写单元测试时出错

php小編小新在這篇文章中將為您介紹在Go語言中編寫單元測試時出現的一種常見錯誤,即斷言錯誤。當我們在編寫單元測試時,有時會遇到無法確定回傳值的情況,這會導致意外的方法呼叫錯誤。在本文中,我們將討論這個問題的原因和解決方法,幫助您更好地處理斷言錯誤,確保單元測試的準確性和可靠性。

問題內容

我在go 中使用testify 為我的服務方法編寫單元測試,除了更新方法之外,所有方法都工作正常,因為在更新方法中我在更新方法中呼叫同一服務的另一個方法(“getbyid”) .

在我的服務中實作 update 方法:

func (ts *teamservice) update(team *team.team) apperror {
    t, err := ts.teamrepo.getbyid(team.id)
    if err != nil {
        return err
    }
    if t.teamownerid != team.teamownerid {
        return newforbiddenerror(forbiddenerr)
    }

    return ts.teamrepo.update(team)
}

mockrepo 更新方法:

func (t *teamrepomock) update(team *team.team) apperror {
    args := t.called(team)
    if args.error(0) != nil {
        return newnotfounderror(args.error(0))
    }

    return nil
}

測試的實作:

func testupdate(t *testing.t) {
    _, teamidgen, playeridgen := setupconfig()

    t.run("update a team", func(t *testing.t) {
        teamrepo, _, ts := setupteamservice(teamidgen, playeridgen)

        teamrepo.on("update", testteam1).return(nil)
        result := ts.update(testteam1)

        assert.nil(t, result)
    })

    t.run("update a team fails", func(t *testing.t) {
        teamrepo, _, ts := setupteamservice(teamidgen, playeridgen)

        expected := oopserr
        teamrepo.on("update", testteam1).return(expected)
        result := ts.update(testteam1)

        assert.equalvalues(t, expected.error(), result.error())
    })
}

現在,當我執行測試時,出現以下錯誤:

--- FAIL: TestUpdate (0.01s)
    --- FAIL: TestUpdate/Update_a_team (0.01s)
panic: 
assert: mock: I don't know what to return because the method call was unexpected.
    Either do Mock.On("GetByID").Return(...) first, or remove the GetByID() call.
    This method was unexpected:
        GetByID(string)
        0: ""
    at: [/home/waleem/Desktop/project/eazykhel_server/services/teamservice/team_service_init_test.go:18 /home/waleem/Desktop/project/eazykhel_server/services/teamservice/team_service.go:146 /home/waleem/Desktop/project/eazykhel_server/services/teamservice/team_service_test.go:277] [recovered]
    panic:

我嘗試在測試函數實作中呼叫.on("update") 之前和之後呼叫mock.on("getbyid") ,但它不起作用,而且我還修改了mockrepo update函數,但它沒用。

解決方法

讓我嘗試幫助您解決問題。我通過一些簡化複製了該存儲庫,只是為了發布相關程式碼。如果我在您的解決方案中沒有錯,有一個服務(teamservice)呼叫底層套件(teamrepo)提供的一些方法。您想要測試 teamservice 結構的 update 方法。回顧之後,讓我先展示程式碼,然後我將嘗試解釋每個檔案:

repo/repo.go

package repo

type team struct {
    id          int
    teamownerid int
    name        string
}

type teamrepo struct{}

func (t *teamrepo) getbyid(id int) (team, error) {
    return team{id: id, teamownerid: id, name: "myteam"}, nil
}

func (t *teamrepo) update(team team) error {
    return nil
}

在此文件中,我們可以找到要模擬的方法。方法是:getbyidupdate。顯然,這不是您的實際程式碼,但現在並不重要。

services/service.go

package services

import (
    "errors"

    "testifymock/repo"
)

type teamservice struct {
    tr teamrepointerface
}

func newteamservice(repo teamrepointerface) *teamservice {
    return &teamservice{
        tr: repo,
    }
}

type teamrepointerface interface {
    getbyid(id int) (repo.team, error)
    update(team repo.team) error
}

func (ts *teamservice) update(team *repo.team) error {
    t, err := ts.tr.getbyid(team.id)
    if err != nil {
        return err
    }

    if t.teamownerid != team.teamownerid {
        return errors.new("forbidden")
    }

    return ts.tr.update(*team)
}

在這裡,我們可以在測試程式碼中看到將成為我們的被測系統的服務 (sut)。透過依賴注入,我們將利用透過介面 teamrepointerface 注入的 repo 套件提供的功能。

services/service_test.go

package services

import (
    "errors"
    "testing"

    "testifymock/repo"

    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/mock"
)

// 1. declare the mock struct
type teamRepoMock struct {
    mock.Mock
}

// 2. implement the interface
func (m *teamRepoMock) GetByID(id int) (repo.Team, error) {
    args := m.Called(id)

    return args.Get(0).(repo.Team), args.Error(1)
}

func (m *teamRepoMock) Update(team repo.Team) error {
    args := m.Called(team)

    return args.Error(0)
}

func TestUpdate(t *testing.T) {
    t.Run("GoodUpdate", func(t *testing.T) {
        // 3. instantiate/setup mock
        repoMock := new(teamRepoMock)
        repoMock.On("GetByID", 1).Return(repo.Team{ID: 1, TeamOwnerID: 1, Name: "test"}, nil).Times(1)
        repoMock.On("Update", repo.Team{ID: 1, TeamOwnerID: 1, Name: "test"}).Return(nil).Times(1)

        sut := NewTeamService(repoMock)
        err := sut.Update(&repo.Team{ID: 1, TeamOwnerID: 1, Name: "test"})

        // 4. check that all expectations were met on the mock
        assert.Nil(t, err)
        assert.True(t, repoMock.AssertExpectations(t))
    })

    t.Run("BadUpdate", func(t *testing.T) {
        // 3. instantiate/setup mock
        repoMock := new(teamRepoMock)
        repoMock.On("GetByID", 1).Return(repo.Team{ID: 1, TeamOwnerID: 1, Name: "test"}, nil).Times(1)
        repoMock.On("Update", repo.Team{ID: 1, TeamOwnerID: 1, Name: "test"}).Return(errors.New("some error while updating")).Times(1)

        sut := NewTeamService(repoMock)
        err := sut.Update(&repo.Team{ID: 1, TeamOwnerID: 1, Name: "test"})

        // 4. check that all expectations were met on the mock
        assert.Equal(t, "some error while updating", err.Error())
        assert.True(t, repoMock.AssertExpectations(t))
    })
}

在程式碼中,您可以找到一些註解以更好地詳細說明所發生的情況。正如您所猜測的,問題是程式碼中缺少此呼叫:

repomock.on("getbyid", 1).return(repo.team{id: 1, teamownerid: 1, 姓名: "test"}, nil).times(1)

#

如果您運行我的解決方案,它也應該適合您。
如果這解決了您的問題或還有任何其他問題,請告訴我!

以上是斷言:模擬:我不知道要回傳什麼,因為方法呼叫是意外的 在 Go 中編寫單元測試時出錯的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除