Unit Testing

Vitalii Symon, 31 December 2010

jigsaw pieces*

Unit testing is a popular tool and its advantages are obvious – rapid, accurate testing which is able to cover whole system of any complexity within minutes.  But, this approach takes some time and effort. A large number of developers do unit tests for simplest components which do not do serious integration like database or some 3rd-party API.

Today I’ll post couple of samples how to cope with database and other tests which need to create, update or remove items – so the database will not be full of rubbish records produced by each separate test run. The task is clear – create test records before test and delete them when everything is completed. Microsoft Visual Studio offers a solution for such kind of tests.

As almost everything in Unit Testing by Microsoft, those events are marked using custom attributes. So what you need to do is:

1. Add start method

        [ClassInitialize()]
        public static void MyClassInitialize(TestContext testContext)
        {
            // init your test class here
        }

2. Add clean up method

        [ClassCleanup()]
        public static void MyClassCleanup()
        {
            // clean test records here
        }

The first method will be launched automatically before performing any tests; the second one will be executed once last test is finished. This allows writing complex tests which will be able to check not logic only, but database compliance and integrity as well. This tool is also nice for testing CRM applications and plugins which are highly bound to the system and there is almost no chance to test them separately.

*Image from http://www.annastan.com/wp-content/uploads/2010/11/puzzle.jpg