开发者

AssemblyCleanup() after test fail/exception

开发者 https://www.devze.com 2022-12-29 12:36 出处:网络
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 databa

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号