I tend to name my unit tests with the following convention: NameOfMethod_Inputs_Should_ExpectedResult
For example, I have a method called Multiply which multiplies two integer parameters. If I have a test case to test this method with 2 integers 3 and 4, the test would be called Multiply_3_And_4_Should_Be_12
This has been working well for me until I recently come across TestCaseData from NUnit. TestCaseData allows you to set as many arguments for the test as you want and allows you to have spaces in your test name. So for the above example, using TestCaseData, you could name it as “Multiply 3 and 4 should be 12”.
public class Calculator { public static int Multiply(int x, int y) { return x*y; } } [TestFixture] public class CalculatorTests { private static IEnumerable<TestCaseData> CalculatorTestCaseData { get { yield return new TestCaseData(3, 4, 12).SetName("Multiply 3 and 4 should be 12"); yield return new TestCaseData(4, 5, 20).SetName("Multiply 4 and 5 should be 20"); } } private static IEnumerable<TestCaseData> CalculatorTestCaseDataWithZero { get { yield return new TestCaseData(0, 4, 12).SetName("Multiply 0 and 4 should be 0"); yield return new TestCaseData(5, 0, 20).SetName("Multiply 5 and 0 should be 0"); } } [Test] [TestCaseSource(typeof(CalculatorTests), nameof(CalculatorTestCaseData))] [TestCaseSource(typeof(CalculatorTests), nameof(CalculatorTestCaseDataWithZero))] public void Calculate_Success(int x, int y, int expected) { Calculator.Multiply(x, y).Should().Be(expected); } }
When you the tests above, you’ll see the nice names in the test runner.
A couple things to note when using TestCaseData:
- The number of arguments on the test must match the number of arguments specified in the TestCaseData.
- The type of arguments on the test must also match the type of arguments specified in the TestCaseData.