Is it possible to execute code once before all tests run?

.NetMstest

.Net Problem Overview


Basically I would like to tell MSTest to execute a bit of code before launching into a series of test runs, essentially what I would like to do is the same thing as sticking some code in Main().

The reason I would like to do this is that I would like to do some logging with log4net during my integration test runs. I cannot just use the log4net.Config.XmlConfigurator assembly attribute since by the time it reads it in my test assembly it has already called LoggerManager. The documentation recommends configuring log4net explicitly at the code entry point - but where is that in my tests?

I need to be able to run my tests in TestDriven.NET and MSTest runner.

.Net Solutions


Solution 1 - .Net

FWIW, you can use the AssemblyInitialize attribute to run code before all unit tests in an assembly executes:

[TestClass]
public class SetupAssemblyInitializer
{
    [AssemblyInitialize]
    public static void AssemblyInit(TestContext context)
    {
        // Initalization code goes here
    }
}

If you have more than one unit test assembly, I'm not aware of anything that encompasses more than one assembly.

As far as I'm aware, this is as close as you can get to a Main equivalent.

Note that the AssemblyInitialize-decorated method must be in a TestClass-decorated class which contains at least one TestMethod-decorated method, otherwise it will not be executed!

Solution 2 - .Net

For completion, these are the "run code before" options for MSTest:

  • Use [AssemblyInitialize] to run code once per assembly, before any test in that assembly runs.
  • Use [ClassInitialize] to run code once per class, before any test in the class where the method is defined.
  • Use [TestInitialize] to run code before each and every test in the class where the method is defined.

Solution 3 - .Net

I see this in the MS Test header.

// Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext) { }

This would run before the tests in one class.

Sounds like you want to run something before all of the tests.

There is also the setup script option in the test run config.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorge MauerView Question on Stackoverflow
Solution 1 - .NetMark SeemannView Answer on Stackoverflow
Solution 2 - .NetKonamimanView Answer on Stackoverflow
Solution 3 - .NetMaestro1024View Answer on Stackoverflow