Ale, music and enjoying life.
A few weeks back I noticed that a part of the code that I’d been working on for over a year seemed to be growing in size and needed to be addressed in order to avoid future headaches and pain. The code is by no means monolithic but of a significant size to be a thing in it’s own right and not a quick 15 minute fix. I could see that action was needed in order to support future maintainability and scalability. Here’s 7 tips for refactoring…
Using Moq I was creating a few unit tests and stumbled across an interesting problem. I needed to mock a call to an async method on a service under test that took in a 2 parameters and returned a tuple of 2 values.
I have a loop in production code that has evolved into processing batches of records. I need to modify an existing unit test to accommodate mocking the same method call each time through the loop returning different results on each loop (as it would in production).
Using Moq we can make use of a Queue and Dequeue result sets each time in the loop as follows:
for (var i = 0; i < loop; i++)
{
var jobsInBatch = BuildJobs(batches).ToList();
jobQueue.Enqueue(jobsInBatch);
jobQueue.AddRange(jobsInBatch);
}
_processor.Setup(m => m.GetAllJobs(batches)).Returns(() => jobQueue.Dequeue());
Just some rough notes I made coming from a Moq framework and converting to Rhino Mocks:
ISomethingRepository mockedSomethingRepository = MockRepository.GenerateMock();
var person = new Person { name = “Bob” };
// Act
var something = new Something(mockedSomethingReporsitory);
// Assert
mockedSomethingRepository.AssertWasCalled(x => x.Save(person));
As above but assert on the property….
mockedSomethingRepository.AssertWasCalled(x => x.WasPersonSaved = true);
Similar to Setup with Moq we’d use a Stub to return the desired flow i.e:
ISomethingRepository mockedSomethingRepository = MockRepository.GenerateMock();
mockedSomethingRepository.Stub(x => x.ValidatePerson(Arg.Is.Anything)).Return(true));
ISomethingRepository mockedSomethingRepository = MockRepository.GenerateMock();
mockedSomethingRepository.Stub(x => x.IsValid).Return(true));
You can use GenerateStub here but the above setup for the stub keeps things syntactically the same in all mock setup instances.
In the first example we simply checked that a method was called. If we wanted to check the method was called passing in an object with specific properties we would do the following:
var personId = 23;
mockedSomethingRepository.AssertWasCalled(x => x.Save(Arg.Matches(x => x.Id == personId));
Check out some of my other Mocking tips and tricks….