Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global.asax for Unit Tests?

In my MSTest UnitTest project, before running any tests, I need to execute some commands. Is there a feature, kind of like Global.asax is for web based projects, that will let me kick off something before any tests run?

I should make it clear that when I say "execute some commands", I don't mean DOS commands, but execute some code.

like image 842
AngryHacker Avatar asked Jun 10 '10 21:06

AngryHacker


2 Answers

If I understand correctly, you need to have some initialization code run before you start your tests. If that is indeed the case you should declare a method inside your unit-test class with the ClassInitializeAttribute like this:

[ClassInitialize]
public void ClassSetUp()
{
     //initialization code goes here...
}

Edit: there is also the AssemblyInitializeAttribute that will run before any other tests in assembly

like image 177
bottlenecked Avatar answered Oct 05 '22 22:10

bottlenecked


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.

like image 27
Jeff Sternal Avatar answered Oct 05 '22 23:10

Jeff Sternal