Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 783
Carles Company Avatar asked Aug 25 '26 01:08

Carles Company


1 Answers

There is no need to mock anything. You can use any IComparable object like Integers or Strings.
Check it out:

[TestMethod]
public void YourTestName()
{
    Assert.IsTrue(2.Between(0, 5));
    Assert.IsFalse("a".Between("b", "d"));
}

Keep It Simple.

By the way, I would rename that method to IsBetween instead of just Between. I found it much more fluent.

[TestMethod]
public void YourTestName()
{
    Assert.IsTrue(2.IsBetween(0, 5));
}
like image 177
goenning Avatar answered Aug 27 '26 16:08

goenning