I’m asked to write some unit tests for some functionality, but quite frankly I’m not so sure about the need or usefulness of doing so for this particular piece of code. I’m in no way trying to question the need or usefulness of unit testing in general.
The code in question is very trivial and gets used alot. Basically it’s a wrapper around the .Skip() and .Take() extension methods. In my opinion the legitimacy of the methods as a whole is questionable.
The code is basically this:
public IQueryable<T> Page(IQueryable<T> query, int page, int size)
{
if(query == null) throw new ArgumentNullException("query");
if(page < 0) throw new ArgumentOutOfRangeException("page");
if(page < 0) throw new ArgumentOutOfRangeException("size");
return query.Skip(page * size).Take(size);
}
Of course I can unit test for the expected exceptions, but what else? Could very well be that I’m missing the point, so what’s up with this?
You can test quite a few things here:
Skipwas called with the correct parameter.Takewas called with the correct parameter.Skipwas called beforeTake.Points 2 – 4 are best tested with a mock. A mocking framework comes in handy here.
This kind of testing is called “interaction-based testing”.
You could also use “state-based testing” by calling the method under test with a list with data and check that the returned data is the correct subset.
A test for point 2 could look like this:
This test uses NSubstitute as mocking framework.