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

前端 未结 3 777
广开言路
广开言路 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:06

    The trace output from a ClassInitialize and ClassCleanup appears in the result summary.

    You can access it by doing the following

    1. Open the Test Results windw [ Test -> Windows -> Test Results ]
    2. There should be a link named "Test run completed" on the top left corner of the [Test Results] window.
    3. Click the clink
    4. It should open a window with the header "Result Summary" and it will show the debug trace created during ClassInitialize and ClassCleanup
    0 讨论(0)
  • 2021-01-11 17:11

    You can see the Console output on each test if you double-click the test method in the Test Results pane. It is also present in the .trx xml results file.

    In addition, if you specify the "Define DEBUG constant", you can use the System.Diagnostics.Debug.WriteLine("ClassInitialize Method invoked, yeah."); .. which will end up in the "Output" pane.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题