Domanda

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?

È stato utile?

Soluzione

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");
    }
  }  
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top