
It happens that we need to create few tests for the same method using different input. In such case I was always writing few identical test methods with different names and different values inside them. You can see an example below.
This code is F# but don’t be afraid, it is easy to understand! This post is a continuation of “Unit tests in F# – friendly names”. You can below code on GitHub:
[<Test>] let ``is time 23:59:59 properly parsed``() = //arrange let time = "23:59:59" //act let parsedTime = Time.Parse(time) //assert Assert.That(parsedTime.Hour, Is.EqualTo(23)) Assert.That(parsedTime.Minute, Is.EqualTo(59)) Assert.That(parsedTime.Second, Is.EqualTo(59)) [<Test>] let ``is time 0:0:0 properly parsed``() = //arrange let time = "0:0:0" //act let parsedTime = Time.Parse(time) //assert Assert.That(parsedTime.Hour, Is.EqualTo(0)) Assert.That(parsedTime.Minute, Is.EqualTo(0)) Assert.That(parsedTime.Second, Is.EqualTo(0)) [<Test>] let ``is time 0:01:0 properly parsed``() = //arrange let time = "0:01:0" //act let parsedTime = Time.Parse(time) //assert Assert.That(parsedTime.Hour, Is.EqualTo(0)) Assert.That(parsedTime.Minute, Is.EqualTo(1)) Assert.That(parsedTime.Second, Is.EqualTo(0))
This is nothing but code duplication. We want to avoid something like that and we can use TestCase attribute which is available in nUnit library. Deeper explanation later, let’s see a code after changes first (GitHub):
[<TestCase("0:01:0", 0, 1, 0)>] [<TestCase("0:0:0", 0, 0, 0)>] [<TestCase("23:59:59", 23, 59, 59)>] let ``is time properly parsed``(time, parsedHour, parsedMinute, parsedSecond) = //act let parsedTime = Time.Parse(time) //assert Assert.That(parsedTime.Hour, Is.EqualTo(parsedHour)) Assert.That(parsedTime.Minute, Is.EqualTo(parsedMinute)) Assert.That(parsedTime.Second, Is.EqualTo(parsedSecond))
Much better, huh? We are removing duplicated code and leaving only one method. Now we need to open that method to get input values through parameters. In given example the very first argument is an expected test result, input values are next. Above test method we add TestCase attribute and we provide expected result value and input values in the same order as method’s input parameters. We can add as many TestCase attributes as many cases we want to test.
TestExplorer window inside VisualStudio still will be showing us three tests. In addition it will show input parameter values at the end so we don’t need to put those values inside method name. We gain better readability automatically!

Test Explorer with TestCase examples
For curious: nUnit docs about TestCase.