2

I want to initialize often used variables in [TestInitialize] method, but I don't want the same variables initialized for every test method. Is there a way to distinguish test methods from each other by a decorator or something similar? For example

[TestInitialize]
public Setup()
{
     //pseudocode
     if VariablesContainLetters
       var1 = a; var2 = b; var3 = c;
     else if VariablesContainNumbers
       var4 = 1; var5 = 2; var6 = 3;
}

[TestMethod]
[VariablesContainLetters]
public method1() {}

[TestMethod]
[VariablesContainNumbers]
public method2() {}

So that I can initialize different variables for different TestMethods?

Rich
  • 6,470
  • 15
  • 32
  • 53
  • I ended up writing conditionals based on test method names like this post describes. This is a nice feature. Check it out: https://stackoverflow.com/a/33895194/7201774 if (TestContext.TestName == "testMethodName") – Rich Aug 14 '17 at 19:57

2 Answers2

2

Here is an example of what I think you are trying to accomplish. Declare a Dictionary you can replace string with other types if you wish. Bool, int, objects even.

[TestInitialize]
public Setup()
{
     Dictionary<string, string> variables = new Dictionary<string, string>();
     //pseudocode
     if VariablesContainLetters
       variables.Add("var1", "a");
       variables.Add("var2", "b");
     else if VariablesContainNumbers
       variables.Add("var4", "1");
       variables.Add("var5", "2");
}

[TestMethod]
[VariablesContainLetters]
public method1() {MessageBox.Show(variable["var1"]);} //prints "a"

[TestMethod]
[VariablesContainNumbers]
public method2() {MessageBox.Show(variable["var4"]);} //prints "1"
Bender Bending
  • 729
  • 8
  • 25
  • I'm not sure how to use the [VariablesContainLetters] or [VariablesContainNumbers] decorators. The way it is now they won't work. I believe I need to create a class named VariablesContainLetters that implements the System.Attribute class for this to work. I'm not exactly sure how to do that but I believe that's a start. – Rich Aug 04 '17 at 18:39
1

One possible solution to this is to create private methods within the test class which initialize the variables in the different ways you would like.

Then, within each unit test, have the first line of the test call the desired setup method and then proceed with the rest of the test.

I think that would lead to a more readable design for future test maintainers.

For example:

[TestMethod]
public void UnitTest_Testing_Letters()
{
  InitializeUsingLetters();
  // ...
  // The rest of your unit test
  Assert.AreEqual(a, _var1);
}

[TestMethod]
public void UnitTest_Testing_Numbers()
{
  InitializeUsingNumbers();
  // ...
  // The rest of this unit test
  Assert.AreEqual(1, _var4);
}

private void InitializeUsingLetters()
{
  _var1 = a;
  // ...
}

private void InitializeUsingNumbers()
{
  _var4 = 1;
  // ...
}
Eric Olsson
  • 4,805
  • 32
  • 35