AssemblyCleanup() after test fail/exception
I'm running a f开发者_运维百科ew unit tests that requires a connection to the database. When my test project get initialized, a snapshot of the database is created, and when tests are done the database gets restored back to the snapshot.
Here is the implementation:
[TestClass]
public static class AssemblyInitializer
{
[AssemblyInitialize()]
public static void AssemblyInit(TestContext context)
{
var dbss = new DatabaseSnapshot(...);
dbss.CreateSnapshot();
}
[AssemblyCleanup()]
public static void AssemblyCleanup()
{
var dbss = new DatabaseSnapshot(...);
dbss.RevertDatabase();
}
}
Now this all works, but my problem arise when I have a failing test or some exception. The AssemblyCleanup is of course not invoked, so how can I solve this problem? No matter what happens, the snapshot has to be restored. Is this possible?
Yes, don't do it this way. Somebody might trip over the power cord. Always copy a known-good copy of the database files and attach them. Look in the documentation for the dbase engine you use how to attach.
Your assumption that AssemblyCleanup won't be invoked is wrong. Unless someone might "trip over the power cord" (as Hans suggested above), TestCleanup, ClassCleanup and AssemblyCleanup all execute regardless if there was an exception or not (or test failure).
Note that this is true as long as your test (or code under test) does't spawn new threads that might throw exceptions.
Bottom line: Hans solution is stonger, but for most cases, I find that AssemblyCleanup is good enough and more straight-forward.
精彩评论