Search code examples
c#genericstddextension-methodsmoq

Generic extension method testing


I have a really simple extension method which is constrained for IComparable instances:

public static bool Between<T>(this T comparable, T min, T max) where T : IComparable<T>
{
    return comparable.CompareTo(min) >= 0 && comparable.CompareTo(max) <= 0;
}

Which would be the correct approach to test this method? I tried mocking IComparable instances to no avail... I use NUnit and Moq, but I'm really a noob in TDD.


Solution

  • Try the following in Moq. This will test the case where the value is actually between the provided values.

    var mock = new Mock<IComparable<string>>();
    mock.Setup(x => x.CompareTo("a")).Returns(1).Verifiable();
    mock.Setup(x => x.CompareTo("z")).Returns(-1).Verifiable();
    Assert.IsTrue(mock.Object.Between("a", "z"));
    mock.Verify();
    

    You can modify this fairly quickly to test the negative cases