Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit set test name programmatically

Having this unit test code snippet, taken from NUnit TestCaseSource

[Test, TestCaseSource("DivideCases")]
public void DivideTest(int n, int d, int q)
{
    Assert.AreEqual( q, n / d );
}

static object[] DivideCases =
{
    new object[] { 12, 3, 4 },
    new object[] { 12, 2, 6 },
    new object[] { 12, 4, 3 } 
};

It correctly runs the test three times, but in the output I get the same test method name, "DivideTest" run three times.

I would like to programmatically change/set the name of the test according to some values defined in the code.

Does anyone have an idea on how to do it?

like image 549
Attila Avatar asked Sep 22 '26 17:09

Attila


1 Answers

In the link that you posted, there is a snippet where you explicitly create the TestCaseData objects via a method linked via the TestCaseSource attribute. When you do this, you get control to set the name of each individual Test Case. See the last TestCaseData instance below.

 public static IEnumerable TestCases
  {
    get
    {
      yield return new TestCaseData( 12, 3 ).Returns( 4 );
      yield return new TestCaseData( 12, 2 ).Returns( 6 );
      yield return new TestCaseData( 12, 4 ).Returns( 3 );
      yield return new TestCaseData( 0, 0 )
        .Throws(typeof(DivideByZeroException))
        .SetName("DivideByZero")
        .SetDescription("An exception is expected");
    }
  }  
like image 56
Gishu Avatar answered Sep 24 '26 05:09

Gishu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!