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 {}然后返回[] resources.DeviceListDataReturn { { 姓氏:" f", 姓名:" n", FirmwareVersion:" 1.0", }, 在第二次。
答案 0 :(得分:0)
对于根据电话号码采取不同行动的任何功能或方法,此信息需要在其中提供。
最简单的方法是在每次调用时添加和递增计数器,并在函数内部检查计数器的当前值,并根据其值采取不同的行为:
type MockGetDeviceList struct {
returnResult []resources.DeviceListDataReturn
returnError string
getCount int
}
func (m *MockGetDeviceList) Get(familyName string, name string,
firmwareVersion string) ([]resources.DeviceListDataReturn, string) {
m.getCount++
if m.getCount == 1 {
// First call:
return nil, m.returnError
}
// Sencond and subsequent calls:
return m.returnResult, ""
}
另一种解决方案是在第一次调用后替换模拟对象/函数,但这种解决方案更难理解,更脆弱,维护更少。