Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 erase possibly inserted dummy values, therefore, this cleaning up happens in methods marked with the attributes [ClassInitialize()] and [ClassCleanup()].

(I know that a better way would be to use an in-memory database, but it is not really doable so far as we depend on lots of stored procs....)

I would like to output some information about the results of the cleaning up, but I can not find a way to get the output in the test results with VISUAL Studio 2010.

This is what I am doing so far :

        ///... lots of stuff before ...

        //global for the test run
        private static TestContext context;

        //for each test
        private IRepository repo;

        #region Initialisation and cleanup

        /// <summary>
        /// Execute once before the test-suite
        /// </summary>
        [ClassInitialize()]
        public static void InitTestSuite(TestContext testContext)
        {
            context = testContext;    
            removeTestDataFromDb();    
        }

        [ClassCleanup()]
        public static void CleanupTestSuite()
        {
            removeTestDataFromDb();
        }

        private static void removeTestDataFromDb()
        {
            context.WriteLine("removeTestDataFromDb starting");
            using (ISession session = NHibernateHelper.OpenSession())
            {    
                IDbConnection cn = session.Connection;
                IDbCommand cmd = cn.CreateCommand();
                //remove anyt test data
                cmd.CommandText = @"DELETE FROM SomeTable
                    WHERE somefield LIKE 'easyToFindTestData%Test'";
                int res = cmd.ExecuteNonQuery();    
                context.WriteLine("removeTestDataFromDb done - affected {0} rows", res);
            }
        }


        [TestInitialize()]
        public void InitTest()
        {
            repo = new MyRepositoryImplementation();
        }

        [TestCleanup()]
        public void CleanupTest()
        {
            //cleanup       
            repo = null;
        }

        #endregion

I'm trying to use context.WriteLine() ...

I also tried just using Console.WriteLine() with the same results.

How do you write to standard output in the ClassInitialize part and where can you access that output ?

like image 450
tsimbalar Avatar asked Dec 07 '10 07:12

tsimbalar


People also ask

What is ClassInitialize attribute in MS test?

The method decorated by [ClassInitialize] is called once before running the tests of the class. In some cases, you can write the code in the constructor of the class. The method decorated by [ClassCleanup] is called after all tests from all classes are executed.

Which are the steps to write the unit tests?

A unit test typically features three different phases: Arrange, Act, and Assert (sometimes referred to as AAA). For a unit test to be successful, the resulting behavior in all three phases must be in line with expectations.


2 Answers

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.

like image 164
Steven Avatar answered Sep 22 '22 16:09

Steven


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
like image 39
Hasani Blackwell Avatar answered Sep 19 '22 16:09

Hasani Blackwell