Chr*_*ris 11 c# unit-testing rhino-mocks
当使用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")));
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果测试失败并显示此消息...
Rhino.Mocks.Exceptions.ExpectationViolationException:ISomeInterface.Write(等于hello); 期望#1,实际#0.
......你不知道它是否失败,因为
A.'Write'永远不会被调用 - 或 -
B.'Write'实际上是调用的,但参数不正确
如果B是导致失败的原因那么如果消息读取的内容会更加清晰:
Rhino.Mocks.Exceptions.ExpectationViolationException:ISomeInterface.Write(string arg):调用了方法,但参数不正确:预期:hello,Actual:bye
我可以自己解决这个缺点(通过某种方式为Rhino编写自定义匹配器)或者我只需要编写一个手动模拟器吗?
Chr*_*ris 10
我通过使用Rhino提供的"匹配"语法找到了一个简单的解决方案:
[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>.Matches(s => Equal(s, "hello"))));
}
private static bool Equal(string s1, string s2)
{
Assert.That(s1, Is.EqualTo(s2), "Unexpected argument");
return true;
}
Run Code Online (Sandbox Code Playgroud)
当然,它有点笨拙,但它完成了工作.如果有更好的方法,请告诉我.