Rhino Mocks - AssertWasCalled:如何在参数不正确时改进不清楚的诊断消息
恕我直言,当使用 AssertWasCalled 来验证是否已使用特定参数调用方法时,Rhino Mocks 会生成不清楚的诊断消息。
示例:
interface ISomeInterface
{
void Write(string s);
}
[TestFixture]
public class SomeTests
{
[Test]
public void WriteShouldBeCalledWithCorrectArguments()
{
// Arrange
var mock = MockRepository.GenerateMock<ISomeInterface>();
var sut = new SomeClass(mock);
// Act
sut.DoSomething();
// Assert
mock.AssertWasCalled(x => x.Write(Arg<string>.Is.Equal("hello")));
}
}
现在,如果测试失败并显示此消息...
Rhino.Mocks.Exceptions.ExpectationViolationException : ISomeInterface.Write(等于 hello);预期 #1,实际 #0。
...您无法知道它是否失败,因为
A.“写入”从未被调用 - 或 -
B. 实际上调用了“Write”,但参数不正确
如果 B 是失败的原因,那么如果消息读取如下内容,则会更加清晰:
Rhino.Mocks.Exceptions.ExpectationViolationException : ISomeInterface.Write(string arg): 方法被调用,但参数不正确:预期:你好,实际:再见
我可以自己修复这个缺点吗(通过以某种方式为Rhino编写自定义匹配器)或者我只是有为此编写手动模拟?
IMHO, Rhino Mocks produces an unclear diagnostic message when AssertWasCalled is used in order to verify that a method has been called with a specific argument.
Example:
interface ISomeInterface
{
void Write(string s);
}
[TestFixture]
public class SomeTests
{
[Test]
public void WriteShouldBeCalledWithCorrectArguments()
{
// Arrange
var mock = MockRepository.GenerateMock<ISomeInterface>();
var sut = new SomeClass(mock);
// Act
sut.DoSomething();
// Assert
mock.AssertWasCalled(x => x.Write(Arg<string>.Is.Equal("hello")));
}
}
Now, if the test fails with this message...
Rhino.Mocks.Exceptions.ExpectationViolationException : ISomeInterface.Write(equal to hello); Expected #1, Actual #0.
... you cannot know if it fails because
A. 'Write' is never invoked -or-
B. 'Write' is in fact invoked but with the incorrect argument
If B would be the cause of the failure then it would be so much clearer if the message would read something like this:
Rhino.Mocks.Exceptions.ExpectationViolationException : ISomeInterface.Write(string arg): Method was called but with the incorrect arguments: Expected: hello, Actual: bye
Can I fix this shortcoming myself (by writing custom matchers for Rhino in some way) or do I simply have to write a manual mock for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通过使用 Rhino 提供的“匹配”语法找到了一个简单的解决方案:
当然,它有点笨拙,但它可以完成工作。如果有更好的方法,请告诉我。
I've found a simple solution by using the "Matches" syntax provided by Rhino:
Sure, it's a little clumsy but it gets the job done. If there is a better way of doing it, please let me know.
您可以使用 GetArgumentsForCallsMadeOn 来获取传递的参数并断言它们:
You could use
GetArgumentsForCallsMadeOn
to get passed arguments and assert them: