Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 可以为任意输入训练Rhinomock吗?_C#_Unit Testing_Mocking_Rhino Mocks - Fatal编程技术网

C# 可以为任意输入训练Rhinomock吗?

C# 可以为任意输入训练Rhinomock吗?,c#,unit-testing,mocking,rhino-mocks,C#,Unit Testing,Mocking,Rhino Mocks,我正在尝试为一段使用拼写校正器的代码设置单元测试。我已经正确地注入了代码依赖项,因此在Rhinomock中设置存根不是问题,但是我为测试创建的文本块有50个单词长,我真的不希望有50行类似这样的代码: spellingCorrector.Stub(x => x.CorrectWord("the")).Return("the"); spellingCorrector.Stub(x => x.CorrectWord("boy")).Return("boy"); spellingCorre

我正在尝试为一段使用拼写校正器的代码设置单元测试。我已经正确地注入了代码依赖项,因此在Rhinomock中设置存根不是问题,但是我为测试创建的文本块有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");
为了单元测试的目的,我认为假设单词拼写正确是可以的。有没有一种方法可以让Rhinomock简单地遵循返回的规则,效果是:

spellingCorrector.Stub(x => x.CorrectWord(y)).Return(y);

您可以使用
IgnoreArguments()
方法:

spellingCorrector
    .Stub(x => x.CorrectWord(null))
    .IgnoreArguments()
    .Return(y);
这样,无论将什么值传递给
CorrectWord
方法,它都将返回
y


更新:

在你的评论之后,它更加清晰:

Func<string, string> captureArg = arg => arg;
spellingCorrector.Stub(x => x.CorrectWord(null)).IgnoreArguments().Do(captureArg);
Func captureArg=arg=>arg;
spellingCorrector.Stub(x=>x.CorrectWord(null)).IgnoreArguments().Do(captureArg);

这将使用作为参数传递的任何值作为返回值。如果需要对此返回值执行一些转换,请调整
captureArg
委托。

对于类似的复杂情况,不要使用Rhinomock,而是编写自己的小存根类。我会用一本包含所有需要更正的单词的字典来支持它,如果字典里没有这个单词,我会返回它


创建mock只是为了让这类事情变得更容易。如果使用Mock不容易(或者更重要的是,可读性更高),只需编写代码。

如果您不是特别喜欢Rhinomock,可以使用:

spellingCorrector.Setup(x=>x.CorrectWord(It.IsAny()))
.返回(x=>x);

关闭,但不是我所需要的。我需要它来归还放进去的东西,而不是每次都是一样的东西。
spellingCorrector.Setup(x => x.CorrectWord(It.IsAny<string>()))
    .Returns(x => x);