Display TestCase name in NUnit when using arrays or generics

I am trying to use TestCaseSource in NUnit to run multiple tests with one of the 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 that the name displayed in the test runner (I use the NUnit testing adapter) is useless, they all display as test_chop(0,System.Int32[]) or if List used and then test_chop(0,System.Collections.Generic.List`1[System.Int32]) .

How to save a readable test and give a useful test name to a test in a test runner? I tried a few things, but I still get the name mentioned above.

+5
source share
2 answers

Use the SetName function to name Test.

 new TestCaseData(3, new List<int> {}).Returns(-1).SetName("test_chop_List<int>"), 
+2
source

This solution I went with first 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 this to create a 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 that NUnit should generate more useful names, but I found this the easiest way to solve my problem, and if I want to deal with exceptions, I could just create another method to handle them.

Note. Remember to enable using System.Collections; and using System.Collections.Generic; .

+1
source

Source: https://habr.com/ru/post/1206889/


All Articles