How to write output in the [ClassInitialize()] of a Unit Test class?

前端 未结 3 803
广开言路
广开言路 2021-01-11 16:36

I am writing some unit tests for the persistence layer of my C#.NET application. Before and after the tests of a test class execute, I want to do some cleaning up to

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-11 17:20

    The [ClassInitialize] and [ClassCleanup] run just once for all the tests in that class. You'd be better of using [TestInitialize] and [TestCleanUp] which run before and after each test. Also try wrapping the complete test in a database transaction. This way you can simply rollback the operation (by not committing the transaction) and your database stays in a consistent state (which is essential for trustworthy automated tests).

    A trick I do for integration tests is to define a base class that all my integration test classes can inherit from. The base class ensures that each test is ran in a transaction and that this transaction is rolled back. Here is the code:

    public abstract class IntegrationTestBase
    {
        private TransactionScope scope;
    
        [TestInitialize]
        public void TestInitialize()
        {
            scope = new TransactionScope();
        }
    
        [TestCleanup]
        public void TestCleanup()
        {
            scope.Dispose();
        }
    }
    

    Good luck.

提交回复
热议问题