C# Unit Testing Generics – Do All Accepted Types Need Unit Tests?

cgenericsunit testing

For a method whose signature looks like this:

public T Add<T>(T first, T second) where T : struct, IEquatable<T>, IComparable<T>

which can work with all of the integral types, do I need to write tests for each of those, e.g.

public void Test_Add_Int()
{
    Assert.That(Add<int>(10, 20), Is.EqualTo(30));
}

public void Test_Add_UInt()
{
    Assert.That(Add<uint>(10, 20), Is.EqualTo(30));
}

public void Test_Add_Long()
{
    Assert.That(Add<long>(10, 20), Is.EqualTo(30));
}

...

or is it sufficient to only have Test_Add_Int?

Best Answer

Do I need to unit test a generic method with all accepted types?

It depends. The types accepted by a generic method are just as much an input parameter as the values that you pass as arguments and the same considerations for testing apply.

This means that if it is really important that your function works correctly for certain types, you should test with those types. If you believe that int and uint are similar enough that if the function works for one, you are confident that it will also work for the other, then you can choose to test with only one of the types. This consideration can also be made over ranges of the value inputs to the tested function.

For example, for your Add<> method, I would consider int, long and uint similar enough within the range of values that doesn't overflow in any of the types that I wouldn't duplicate the tests for multiple types, but I would add type-specific tests around the boundaries of int and uint.