Search code examples
c#unit-testingnunit

How to make unit test methods shorter


I have some unit tests. Like this:

[TestFixture]
public class Tests
{
    [SetUp]
    public void Setup()
    {
    }
}
    

But it looks like almost the same code. Is it possible to write this shorter?

I am using NUnit testing framework.

And this is the code:

public class Parcel
{
    
 //Some code
    
}

It works now


Solution

  • You can use TestCase instead of Test attribute to run the same test code with different data, e.g.

    [TestCase(0.02m, "Name: parcel - Postal code 2582Cd - Weight 0,02 - Value 0,0 - Department Mail")]
    [TestCase(2m, "Name: parcel - Postal code 2582Cd - Weight 2 - Value 0,0 - Department Regular")]
    public void ParcelsWithSpecificWeightShouldBeSpecificToString(decimal weight, string expected)
    {
        var parcel = new Parcel { Name="parcel", PostalCode = "2582Cd", Weight = weigth, Value = 0.0m };
        Assert.AreEqual(expected, parcel.ToString());
    }
    

    But in fact you are testing the Department property, so I would recommend not to test parcel.ToString(), but parcel.Department:

    [TestCase(0.02m, "Mail")]
    [TestCase(2m, "Regular")]
    public void ParcelsWithSpecificWeightShouldBeSpecificDepartment(decimal weight, string expected)
    {
        var parcel = new Parcel { Name="parcel", PostalCode = "2582Cd", Weight = weigth, Value = 0.0m };
        Assert.AreEqual(expected, parcel.Department);
    }