Global test initialize method for MSTest

C#Mstest

C# Problem Overview


Quick question, how do I create a method that is run only once before all tests in the solution are run.

C# Solutions


Solution 1 - C#

Create a public static method, decorated with the AssemblyInitialize attribute. The test framework will call this Setup method once per test run:

[AssemblyInitialize]
public static void MyTestInitialize(TestContext testContext)
{}

For TearDown its:

[AssemblyCleanup]
public static void TearDown() 
{}

EDIT:

Another very important detail: the class to which this method belongs must be decorated with [TestClass]. Otherwise, the initialization method will not run.

Solution 2 - C#

Just to underscore what @driis and @Malice said in the accepted answer, here's what your global test initializer class should look like:

namespace ThanksDriis
{
	[TestClass]
	class GlobalTestInitializer
	{
		[AssemblyInitialize()]
		public static void MyTestInitialize(TestContext testContext)
		{
			// The test framework will call this method once -BEFORE- each test run.
		}
		
		[AssemblyCleanup]
		public static void TearDown() 
		{
			// The test framework will call this method once -AFTER- each test run.
		}
	}
}

Solution 3 - C#

Sorry for the crappy formatting...

        /// <summary>
        /// Use TestInitialize to run code before running each test
        /// Runs before every test executes
        /// </summary>
        [TestInitialize()]
        public void TestInitialize()
        {
           ...
           ...
        }


        /// <summary>
        /// Use TestCleanup to run code after each test has run
        /// Runs after every test executes
        /// </summary>
        [TestCleanup()]
        public void TestCleanup()
        {
           ...
           ...
        }

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
QuestionmglmncView Question on Stackoverflow
Solution 1 - C#driisView Answer on Stackoverflow
Solution 2 - C#Mass Dot NetView Answer on Stackoverflow
Solution 3 - C#AllenView Answer on Stackoverflow