Rich
Rich

Reputation: 6561

.NET Unit Testing - How to to distinguish TestMethods from each other for variable initialization

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?

Upvotes: 2

Views: 94

Answers (2)

Eric Olsson
Eric Olsson

Reputation: 4913

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;
  // ...
}

Upvotes: 1

Ubernator
Ubernator

Reputation: 743

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"

Upvotes: 2

Related Questions