I'm writing unit test for testing main.go and inside the function it's call Get function ( DeviceRepo.Get() ) twice then I would like to mock the Get function which return different but I can mock just first time when it called, So I have no idea how do I mock the Get function at the second time?
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)
})
})
}
I would like to mock the Get function return []resources.DeviceListDataReturn{} at first time and then return []resources.DeviceListDataReturn{ { FamilyName: "f", Name: "n", FirmwareVersion: "1.0", }, } in the second time.