是否可以针对任意输入训练 Rhinomocks?
我正在尝试为一段使用拼写校正器的代码设置单元测试。我已经正确注入了代码依赖项,因此在 Rhinomocks 中设置存根不是问题,但是我为测试创建的文本块有 50 个字长,我真的不想有 50 行代码看起来像这样:
spellingCorrector.Stub(x => x.CorrectWord("the")).Return("the");
spellingCorrector.Stub(x => x.CorrectWord("boy")).Return("boy");
spellingCorrector.Stub(x => x.CorrectWord("ran")).Return("ran");
为了我的单元测试的目的,我认为假设单词拼写正确是可以的。有没有办法让 Rhinomocks 简单地遵循返回规则,其效果是:
spellingCorrector.Stub(x => x.CorrectWord(y)).Return(y);
I am trying to set up a unit test for a piece of code that uses a spelling corrector. I have the code properly dependency injected, so setting up the stub in Rhinomocks is not a problem, but the block of text I've created for the test is a good 50 words long and I would really rather not have 50 lines of code that look something like this:
spellingCorrector.Stub(x => x.CorrectWord("the")).Return("the");
spellingCorrector.Stub(x => x.CorrectWord("boy")).Return("boy");
spellingCorrector.Stub(x => x.CorrectWord("ran")).Return("ran");
For the purposes of my unit tests I think assuming that the words are spelled right is okay. Is there a way to get Rhinomocks to simply follow a rule about returning, something to the effect of:
spellingCorrector.Stub(x => x.CorrectWord(y)).Return(y);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
IgnoreArguments()
方法:这样,无论向
CorrectWord
方法传递什么值,它都会返回y
。更新:
在您的评论之后,情况更加清楚:
这将使用作为参数传递的任何值作为返回值。如果您需要对此返回值执行一些转换,请调整
captureArg
委托。You could use the
IgnoreArguments()
method:This way no matter what value is passed to the
CorrectWord
method, it will returny
.UPDATE:
After your comment it is more clear:
This will use whatever value is passed as argument as return value. Adapt the
captureArg
delegate if you need to perform some transformations on this return value.对于像这样复杂的事情,不要使用 RhinoMocks,而是编写您自己的小存根类。我会用一本包含所有应该更正的单词的词典来支持它,如果词典中没有该单词,则返回该单词。
创建模拟只是为了让这种事情变得更容易。如果使用模拟并不容易(或更重要的是,更具可读性),则只需编写代码即可。
For anything complex like this, instead of using RhinoMocks, write your own little stub class. I'd back it with a Dictionary of all the words that should be corrected, and return the word if it isn't in the Dictionary.
Mocks were only created to make this kind of thing easier. If it isn't easier (or more importantly, more readable) to use mocks, just write the code.
如果您不是特别喜欢 Rhinomock,可以使用 Moq:
If you're not particularly attached to Rhinomock, you can use Moq: