NUnit - ExpectedMessage 不同错误
我对 TDD 很陌生,并且正在使用 NUnit 和 Moq。我有一个预计会出现异常的方法,因此我想尝试一下框架功能。
我的测试代码如下所示:
[Test]
[ExpectedException(ExpectedException = typeof(MockException), ExpectedMessage = "Actual differs from expected")]
public void Write_MessageLogWithCategoryInfoFail()
{
string message = "Info Test Message";
Write_MessageLogWithCategory(message, "Info");
_LogTest.Verify(writeMessage =>
writeMessage.Info("This should fail"),
"Actual differs from expected"
);
}
但我总是收到错误消息,指出实际异常消息与预期消息不同的错误消息。我做错了什么?
I am quite new to TDD and am going with NUnit and Moq. I have got a method where I expect an exception, so I wanted to play a little with the frameworks features.
My test code looks as follows:
[Test]
[ExpectedException(ExpectedException = typeof(MockException), ExpectedMessage = "Actual differs from expected")]
public void Write_MessageLogWithCategoryInfoFail()
{
string message = "Info Test Message";
Write_MessageLogWithCategory(message, "Info");
_LogTest.Verify(writeMessage =>
writeMessage.Info("This should fail"),
"Actual differs from expected"
);
}
But I always receive the errormessage that the error message that the actual exception message differs from the expected message. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,Resharper 测试运行程序有一个错误/限制 - 它不处理 ExpectedException 属性。您有 2 个选择:
使用其他测试运行程序(例如 nunit-gui.exe,随 NUnit 一起提供) - 但这种方法使调试测试变得很痛苦
使用以下模式手动捕获并验证异常:
[测试]
公共无效Write_MessageLogWithCategoryInfoFail()
{
尝试
{
string message = "信息测试消息";
}
真是太遗憾了,因为用描述性的方式来表达你期待一个异常要好得多!
附带说明一下,我希望上面的代码仅用于使用框架 - 通常你永远不会捕获 MockExceptions :)
Unfortunately Resharper test runner has a bug/limitation - it doesn't handle the ExpectedException attributes. You have 2 options:
Use some other test runner (e.g. nunit-gui.exe, shipped with NUnit) - but this approach makes it a pain to debug your tests
Catch and validate the exception manually, using the following pattern:
[Test]
public void Write_MessageLogWithCategoryInfoFail()
{
try
{
string message = "Info Test Message";
}
Its a real shame, because the descriptive way of saying that you expect an exception is much nicer!
On a side note I hope that the code above is only for playing with the framework - usually you would never catch MockExceptions :)
您可以使用额外的参数
MatchType = MessageMatch.Regex
。You may use the extra parameter
MatchType = MessageMatch.Regex
.