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

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!


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.

Tags:

.Net

Mstest