Unit test frameworks usually support set up and "tear down" methods for both the entire test fixture and individual tests. MSTest lets you specify which methods to run when with these attributes:
[ClassIntialize()]
public void ClassInitialize() {
// MSTest runs this code once before any of your tests
}
[ClassCleanup()]
public void ClassCleanUp() {
// Runs this code once after all your tests are finished.
}
[TestIntialize()]
public void TestInitialize() {
// Runs this code before every test
}
[TestCleanup()]
public void TestCleanUp() {
// Runs this code after every test
}
Having said that, be careful with the class initialize and cleanup methods if you're running ASP.NET unit tests. As it says in the ClassInitializeAttribute
documentation:
This attribute should not be used on
ASP.NET unit tests, that is, any test
with [HostType("ASP.NET")] attribute.
Because of the stateless nature of IIS
and ASP.NET, a method decorated with
this attribute may be called more than
once per test run.