如何设置模拟函数的返回值?

huangapple go评论86阅读模式
英文:

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, &quot;Foo&quot;})

huangapple
  • 本文由 发表于 2013年10月26日 12:53:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/19602959.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定