Test Cases with NUnit
As a good developer, you write lots of unit tests and this task could be monotonous time to time. I bet that you’ve been in the situation similar to the following code.
[Test]
public void ReturnsTrueForNegativeEvenInteger()
{
int value = -1;
Assert.IsTrue(value.IsEven());
}
[Test]
public void ReturnsTrueForZero()
{
int value = 0;
Assert.IsTrue(value.IsEven());
}
[Test]
public void ReturnsTrueForEvenInteger()
{
int value = 1;
Assert.IsTrue(value.IsEven());
}
[Test]
public void ReturnsFalseForOddInteger()
{
int value = 2;
Assert.IsFalse(value.IsEven());
}
[Test]
public void ReturnsFalseForNegativeOddInteger()
{
int value = -2;
Assert.IsFalse(value.IsEven());
}
As you can see, there is plenty of boiler-plate code and the task you are trying to achieve is pretty simple. Test multiple input values and verify that the expected result matches. There must be a better way.
And there is, but not an obvious one with MSTests, but with NUnit. All of the previous tests could be written as one with the usage of TestCase attribute.
[TestCase(0, Result = true)]
[TestCase(-1, Result = true)]
[TestCase(1, Result = true)]
[TestCase(-2, Result = false)]
[TestCase(2, Result = false)]
public int ReturnsFor(int value)
{
return value.IsEven();
}
Notice, that the attribute serves also as a marker that the method is a unit test, so you don’t have to add another Test attribute.
With this approach names of tests are auto-generated and if you want to change them you can use the TestName parameter.
[TestCase(0, Result = true, TestName = "ReturnsTrueForZero")]
I really like this feature, it simplifies lots of test cases and saves you from writing redundant code. In my opinion, one of the best reasons to switch to NUnit.