gpt4 book ai didi

unit-testing - Golang 模拟函数被调用两次

转载 作者:IT王子 更新时间:2023-10-29 02:21:38 27 4
gpt4 key购买 nike

我正在编写用于测试 main.go 的单元测试,并在函数内部调用 Get 函数 ( DeviceRepo.Get() ) 两次,然后我想模拟返回不同的 Get 函数,但我可以在第一次模拟时模拟它调用了,所以我不知道如何在第二次模拟 Get 函数?

main.go:

type DeviceInterface interface {}
type DeviceStruct struct{}

var DeviceRepo repositories.DeviceRepoInterface = &repositories.DeviceRepoStruct{}

func (d *DeviceStruct) CheckDevice(familyname string, name string, firmwareversion string) string {
deviceList, deviceListErr := DeviceRepo.Get(familyname, name, firmwareversion)

if deviceListErr != "" {
return "some error"
}

if len(deviceList) == 0 {
deviceList, _ := DeviceRepo.Get(familyname, name, "")

if len(deviceList) > 0 {
return "Invalid firmware version."
} else {
return "Unknown device."
}
}

return "Success"
}

main_test.go:

  type MockGetDeviceList struct {
returnResult []resources.DeviceListDataReturn
returnError string
}

func (m *MockGetDeviceList) Get(familyName string, name string, firmwareVersion string) ([]resources.DeviceListDataReturn, string) {
return m.returnResult, m.returnError
}

func Test_CheckDevice_WrongFirmwareVersion(t *testing.T) {
Convey("Test_CheckDevice_WrongFirmwareVersion", t, func() {
familyNameMock := "A"
nameMock := "A"
firmwareVersionMock := "3"

mockReturnData := []resources.DeviceListDataReturn{}

mockReturnDataSecond := []resources.DeviceListDataReturn{
{
FamilyName: "f",
Name: "n",
FirmwareVersion: "1.0",
},
}

deviceModel := DeviceStruct{}

getDeviceList := DeviceRepo
defer func() { DeviceRepo = getDeviceList }()
DeviceRepo = &MockGetDeviceList{returnResult: mockReturnData}

getDeviceList = DeviceRepo
defer func() { DeviceRepo = getDeviceList }()
DeviceRepo = &MockGetDeviceList{returnResult: mockReturnDataSecond}

expectReturn := "Invalid firmware version."

actualResponse := deviceModel.CheckDevice(familyNameMock, nameMock, firmwareVersionMock)

Convey("Checking check-device wrong firmware version", func() {
So(actualResponse, ShouldEqual, expectReturn)
})
})
}

我想模拟 Get 函数 return []resources.DeviceListDataReturn{} 第一次然后 return []resources.DeviceListDataReturn{{ 姓氏:“f”, 名称:“n”, 固件版本:“1.0”, }, } 在第二次。

最佳答案

您可以使用 https://pkg.go.dev/github.com/stretchr/testify/mock#Call.Once

mock.On("Get", mock.Anything).Return(mockReturnData).Once()
mock.On("Get", mock.Anything).Return(mockReturnData2).Once()

或者如果你知道你可以传递什么参数那么你可以这样做

mock.On("Get", "lastName", "name", "version").Return(mockReturnData)
mock.On("Get", "lastName_2", "name_2", "version_2").Return(mockReturnData2)

关于unit-testing - Golang 模拟函数被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46319732/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com