在 NUnit 中捕获断言失败的正确方法
我正在为我的数据库编写集成测试,我有一个问题。在测试方法开始时,我向数据库添加一些对象,在方法结束时我应该删除它。
所以我有这样的代码:
var group = new ContactGroup { Name = UserLogin + "_test_group" };
group.ID = _provider.AddGroup(UserLogin, group);
Assert.That(_provider.GetGroup(UserLogin, group.ID), Is.Not.Null);
_provider.RemoveGroup(UserLogin, group.ID);
要点是,如果断言失败,RemoveGroup 将不会被执行。我能做什么呢?
如果我尝试这样做:
var group = new ContactGroup { Name = UserLogin + "_test_group" };
group.ID = _provider.AddGroup(UserLogin, group);
try
{
Assert.That(_provider.GetGroup(UserLogin, group.ID), Is.Not.Null);
}
finally
{
_provider.RemoveGroup(UserLogin, group.ID);
}
我应该像这样重新抛出 AssertionException 吗
catch (AssertionException)
{
throw;
}
?
I'm writing an integration tests for my database, and I've got one question. At the beginning of a test method I'm adding some objects to database and at the end of the method I should remove it.
So I've got a code like:
var group = new ContactGroup { Name = UserLogin + "_test_group" };
group.ID = _provider.AddGroup(UserLogin, group);
Assert.That(_provider.GetGroup(UserLogin, group.ID), Is.Not.Null);
_provider.RemoveGroup(UserLogin, group.ID);
The point is that if assertion fails, RemoveGroup won't be executed. What can I do about it?
If i try this:
var group = new ContactGroup { Name = UserLogin + "_test_group" };
group.ID = _provider.AddGroup(UserLogin, group);
try
{
Assert.That(_provider.GetGroup(UserLogin, group.ID), Is.Not.Null);
}
finally
{
_provider.RemoveGroup(UserLogin, group.ID);
}
should I rethrow AssertionException like this
catch (AssertionException)
{
throw;
}
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在数据库集成测试中处理清理的一种方法是在事务中执行测试,然后在测试完成后回滚。
One way to handle cleanup in database integration tests is to execute the test in a transaction, which is then rolled back once the test has completed.
您根本不需要 at
catch
子句。在 C# 中,try {... throw ...} finally {...}
将执行finally
子句,然后将异常向上发送到堆栈中最近的位置catch
,如果没有,则退出程序顶部。因此将完全按照您想要的方式进行:运行 Cleanup() ,然后从断言中终止。
You don't need at
catch
clause at all. In C#, atry {... throw ...} finally {...}
will execute thefinally
clause and then send the exception up the stack to the nearestcatch
, or out the top of the program if none. Thuswill do exactly what you want: run
Cleanup()
and then die from the assertion.使用拆解方法。每次测试后都会立即执行拆解方法。
Use the a tear down method. The tear down method is executed right after every test.
DBUnit 人员建议在启动时而不是关闭时进行销毁(良好的设置不需要清理!) 这就是我所做的。因此,测试开始时会删除测试不需要的任何数据。
The DBUnit people recomemend destorying on start up rather than shutdown (Good setup don't need cleanup!) and is what I do. So the start of the test removes any data the test does not expect.