Unit Test Setup and Teardown

A good practice for your unit tests is to write them for a known state of the system; this includes the database, files, and anything that makes up the entire system. This ensures that developers can rely on these items being there when they write their tests. Of course, the tests themselves often disrupt this state. You might have a test that deletes data, changes it, adds new records, and the like. In this case, you need to be able to reinitialize the state of the system prior to executing your tests (or after executing your tests) to ensure both a steady state to test against and a one-click test run experience for developers (another good practice for unit testing).

You typically need to write code to keep your system in a steady state. This code might copy a known good test database down to the test directory (you could also do this with a DeploymentItem attribute); reset your database using SQL; use a data generation plan to create your database; copy files; or verify other deployment items.

The code to reset your system is specific to your environment. However, to ensure this code is called when your tests run, you have a few attribute classes with which to work: ClassInitialize and ClassCleanup, or TestInitialize and TestCleanup. The former set are run at the start (or end) of a test run in the entire unit test class. The latter are run before (or after) each test executes in a given test class.

In most cases, you run initialize and cleanup at the class level. As an example, if you had a Utilities class that included a method to reset your database, you could ensure it is called by marking a method as ClassInitialize. Note that this method takes a TestContext object (which is passed to it by the unit test framework). A good practice is to reset the system again after the unit tests execute. The following code shows an example of two test methods doing both setup and cleanup.

[ClassInitialize()]
public static void InitTests(TestContext testContext)
{
  Utilities.ResetTestDb();
}

[ClassCleanup()]
public static void CleanupPostTests()
{
  Utilities.ResetTestDb();
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset