23

I am trying to use NUnit with the values attribute so that I can specify many different inputs without having 100 separate tests.

However now I am realizing there are times where I want to use the same set of inputs but on very different test like below.

Is there a way that I can specify all the values in one place, like an array and use the array for each values attribute?

I want to make sure that the test runs as 100 individual tests, instead of 1 test that runs 100 values.

I have looked in the Nunit documentation, but I cannot find a way to accomplish this. Any ideas?

Code:

[Test]
public void Test1([Values("Value1", "Value2", "Value3", ... "Value100")] string value)
{
    //Run Test here
}

[Test]
public void Test2([Values("Value1", "Value2", "Value3", ... "Value100")] string value)
{
    //Run Test here
}

[Test]
public void Test3([Values("Value1", "Value2", "Value3", ... "Value100")] string value)
{
    //Run Test here
}
Sam Plus Plus
  • 4,381
  • 2
  • 21
  • 43

3 Answers3

28

TestCaseSource attribute is suitable here.

See example:

private string[] commonCases = { "Val1", "Val2", "Val3" };

[Test]
[TestCaseSource(nameof(commonCases))]
public void Test1(string value)
{
    ....
}

[Test]
[TestCaseSource(nameof(commonCases))]
public void Test12(string value)
{
    ....
}
had
  • 2,068
  • 1
  • 13
  • 10
Alexander Stepaniuk
  • 6,217
  • 4
  • 31
  • 48
3

You can use FactoryAttribute on test method, instead of ValuesAttribute on param. Read more about this here.

Edit: Alexander is right. FactoryAttribute was a temporary part of API. The right path is to use TestCaseSourceAttribute.

Alberto Solano
  • 7,972
  • 3
  • 38
  • 61
Pavel Bakshy
  • 7,697
  • 3
  • 37
  • 22
0

ValueSource is also an option, especially if you want to combinatorically provide values for multiple test parameters. For example:

public class Tests {
  public static string[] firstValues = { "Val1", "Val2", "Val3" };
  public static string[] secondValues = { "Val4", "Val5", "Val6" };

  [Test, Combinatorial]
  public void Test(
    [ValueSource(typeof(Test), "firstValues")] firstValue,
    [ValueSource(typeof(Test), "secondValues")] secondValue
  )
  {
     ....
  }
}
Kevin
  • 14,655
  • 24
  • 74
  • 124
  • I learned this approach from this helpful answer: https://stackoverflow.com/a/16347477/473792 – Kevin Aug 29 '23 at 05:48