Home :: News ::

Mocking is hard but rewarding..or Is.It

3rd, December 2011
As I continue to pummel my project with new Unit Tests (still no new development for a long time), I am learning much about NUnit and Mocking/Moq.

While attempting to mock a function that takes in 3 parameters and returns a Boolean, I wanted my test to accommodate for 3 particular properties that should return TRUE to the calling function that I am testing. I initially attempted to do the following:

_grid.Setup(s => s.IsCellEmpty(new Cell { X = 0, Y = 0 }, true, _agentList.Object))
.Returns(true)
.Verifiable("IsCellEmpty 1 with correct params was never called");
 
_grid.Setup(s => s.IsCellEmpty(new Cell { X = 1, Y = 0 }, true, _agentList.Object))
.Returns(true)
.Verifiable("IsCellEmpty 2 with correct params was never called");
 
_grid.Setup(s => s.IsCellEmpty(new Cell { X = 0, Y = 1 }, true, _agentList.Object))
.Returns(true)
.Verifiable("IsCellEmpty 3 with correct params was never called");

In essence all of these tests are doing very similar code, however the Cell that is being passed into the function changes. If the function is called and doesn't match any of these rules then it will return FALSE. Unfortunately, not only is this code duplicated, but also this does not work with Moq. For some reason, Moq only seems to check for 2 of these Setups resulting in failed tests later on; so back to the drawing board.

I needed a function that can be applied once but evaluate a number of different possibilities….this is when I found the 'It.Is' functions in the Moq'ing library. Combining a lambda expression with an It.Is I can pass in a number of valid rules all in one function.

_grid.Setup(s => s.IsCellEmpty(It.Is(o => (o.X == 0 && o.Y == 1) || (o.X == 1 && o.Y == 0) || (o.X == 1 && o.Y == 1)), _agentList.Object))
.Returns(true)
.Verifiable("IsCellEmpty with correct params was never called");

By using the 'It.Is' function, I reduced the duplicate Setups and also looks much neater (well in Visual Studio it does…)

Problem SOLVED.

0 Comments Posted by Simon Colmer

Comments:


No comments found
Add a comment
Name:
Email:
Comment:
Security:
X-Volt Studios, Copyright 2009. ©