我正在编写用于测试 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/
我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou
是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent
如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只