英文:
How do you set the return value of a mocked function?
问题
你可以使用gomock的Return方法来指定模拟方法返回特定的值。以下是一个示例:
gw.EXPECT().GetQuestionById(1).Return("特定值")
这将告诉模拟控制器,在调用GetQuestionById方法时,返回值应为"特定值"。你可以根据需要将返回值更改为任何你想要的值。
英文:
I am using gomock to create mock objects for unit testing. The following gives the mock object a method called GetQuestionById and tells the mock controller to expect the method to be called with argument 1:
<!-- language: lang-go -->
gw.EXPECT().GetQuestionById(1)
But how do I specify that the mocked method should return a particular value?
答案1
得分: 7
当你调用gw.EXPECT().GetQuestionById(1)时,它最终会调用模拟控制器上的RecordCall方法。RecordCall返回一个Call对象,而Call对象有一个名为Return的方法,它正是你想要的:
gw.EXPECT().GetQuestionById(1).Return(Question{1, "Foo"})
英文:
When you call gw.EXPECT().GetQuestionById(1), it ends up calling the method RecordCall on the mock controller. RecordCall returns a Call, and Call has a method called Return that does exactly what you want:
<!-- language: lang-go -->
gw.EXPECT().GetQuestionById(1).Return(Question{1, "Foo"})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论