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.A开发者_运维知识库ddGroup(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;
}
?
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.
You don't need at catch
clause at all. In C#, a try {... throw ...} finally {...}
will execute the finally
clause and then send the exception up the stack to the nearest catch
, or out the top of the program if none. Thus
try {
Assert.Fail("BOOM!");
} finally {
Cleanup();
}
will 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.
[TearDown]
public void TearDown()
{
_provider.RemoveGroup(UserLogin, group.ID);
}
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.
精彩评论