Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TestCase display name in NUnit when using Arrays or Generics

I am trying to use TestCaseSource in NUnit to run multiple tests with one of parameters being an array

    private static readonly object[] ReturnChopCases =
    {
        new TestCaseData(3, new List<int> {}).Returns(-1),
        new TestCaseData(3, new List<int> {1}).Returns(1),
        new TestCaseData(1, new List<int> {1,2}).Returns(1),
    };

    [TestCaseSource("ReturnChopCases")]
    public int test_chop(int SearchNumber, int[] SearchArray)
    {
        return Chopper.Chop(3, SearchArray);
    }

The problem is the name displayed in the test runner (I'm using the NUnit Test Adapter) is pretty useless, they all show as test_chop(0,System.Int32[]) or if using a List then test_chop(0,System.Collections.Generic.List`1[System.Int32]).

How do I retain a fairly readable test and give a useful test name to the test in the test runner? I've tried a few things but I still get the name mentioned above.

like image 227
Matt McCabe Avatar asked Sep 30 '22 10:09

Matt McCabe


2 Answers

Use the SetName function to name the Test

new TestCaseData(3, new List<int> {}).Returns(-1).SetName("test_chop_List<int>"),
like image 145
JaredPar Avatar answered Oct 05 '22 08:10

JaredPar


This is the solution I went with, first I created a class for my custom test case

public class CustomTestCase
{
    public CustomTestCase(int SearchNumber, List<int> List, int Result)
    {
        searchNumber = SearchNumber;
        list = List;
        result = Result;
    }
    private int searchNumber;
    private List<int> list;
    private int result;

    public string TestName()
    {
        return string.Format("TestChop({0},{{{1}}})", searchNumber, String.Join(",", list));
    }

    public TestCaseData SimpleTest()
    {
        return new TestCaseData(searchNumber, list).Returns(result).SetName(this.TestName());
    }
}

And then I used that to build the TestCaseSource

private static IEnumerable ReturnChopCases()
{
    List<int> emptyList = new List<int> { };
    yield return new CustomTestCase(3,emptyList,-1).SimpleTest();

    List<int> singleItemList = new List<int> { 1 };
    yield return new CustomTestCase(3, singleItemList, 1).SimpleTest();
    yield return new CustomTestCase(3, singleItemList, 1).SimpleTest();
}

The Test is the same.

I still think NUnit should generate more useful names but I found this the easiest way to deal with my problem and if I want to deal with exceptions I could just create another method to handle those.

NB: Don't forget to include using System.Collections; and using System.Collections.Generic;.

like image 34
Matt McCabe Avatar answered Oct 05 '22 07:10

Matt McCabe