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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With