by abutler
30. March 2011 11:30
I like Moq. For me it has made unit testing almost enjoyable, similar to how jQuery makes writing javascript more bearable.
Today I ran into an issue. I'm mocking System.Data.IDataReader (I'm old school okay, but I'm writing unit tests, so give me a break). So in my code, I call the Read() method of IDataReader until it returns false.
while (reader.Read())
{
// old man code here
}
Moq is great when you setup calls to a method that are somewhat unique. But in this case, each successive call has the same arguments (no argument). So how can I get Read() to return true the first time, then false on any call after that? Well it's probably in the Moq documentation somewhere, but forget that. Here's my solution:
var readerMock = new Mock<System.Data.IDataReader>();
int row = 0;
readerMock.Setup(x => x.Read()).Returns(row++ == 0);
Except that doesn't seem to work quite right, since it evaluates upon setup, not on invocation. Or something. This seems to work:
var readerMock = new Mock<System.Data.IDataReader>();
int row = 0;
readerMock.Setup(x => x.Read()).Returns(() => row++ == 0);
Now it gets evaluated when it is invoked I think. It works at any rate. Plus the inclusion of a lambda expression gives the added benefit of making it appear that I know what I'm doing.
074705b3-59ec-4233-a971-e027180ac34b|0|.0
Category:
Tags: