Programmer and Trainer

In last post we talked about how to start with Unit Testing using NUnit. In this post I will discuss about following two topics,

Test Setup

Test Teardown

You need Test Setup and Test Teardown to remove any dependency between tests. Assume a scenario that

You want to create instance of a particular object before execution of any test

You want to delete a particular file from file system before execution of any test

You want to insert some test data or create some test data before execution of any test etc..

In above stated scenario you may want to create a Test Setup. Test Setup is a piece of code get executed before execution of any test.

Other use case could be that you want to perform a particular task after execution of each test. So once test got executed a certain task should get done and we call that Test Teardown. There could be scenario that

You want to destruct an instance after execution of any test

You want to remove test data after execution of any test

You want to delete a file from file system after execution of any test etc.

In above scenario you may want to create Test Teardown. Test Teardown is piece of code get executed after execution of any test.

In NUnit you can create Test Setup and Test Teardown by using [Setup] and [TearDown] attribute on a function.

So Test Setup can be created as following,

And you can create Test Teardown as following

If there are 5 tests in your test class then these two functions will get executed 5 times. Now let us put our discussion into concrete example. Assume that you are writing Unit Test for a Product class. Product class is defined as following,

The above two function will get executed each time before execution of test and after execution of test. In writing Unit Test , Test SetUp and Test TearDown are very handy and useful. I hope you find this post useful. Thanks for reading.