20.3. Initializing and Cleaning Up

Despite Visual Studio's generating the stub code for test cases you are to write, typically you have to write a lot of setup code whenever you run a test case. Where an application uses a database, that database should be returned to its initial state after each test to ensure that the test cases are completely repeatable. This is also true for applications that modify other resources such as the file system. Visual Studio provides support for writing methods that can be used to initialize and clean up around test cases. (Again, attributes are used to mark the appropriate methods that should be used to initialize and clean up the test cases.)

The attributes for initializing and cleaning up around test cases are broken down into three levels: those that apply to individual tests, those that apply to an entire test class, and those that apply to an entire test project.

20.3.1. TestInitialize and TestCleanup

As their names suggest, the TestInitialize and TestCleanup attributes indicate methods that should be run before and after each test case within a particular test class. These methods are useful for allocating and subsequently freeing any resources that are needed by all test cases in the test class.

20.3.2. ClassInitialize and ClassCleanup

Sometimes, instead of setting up and cleaning up after each test, it can be easier to ensure that the environment is in the correct state at the beginning and end of running an entire test class. Previously, ...

Get Professional Visual Studio® 2008 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.