Wednesday, March 26, 2014

C# Using Moq to mock out parameters on a void method

It has been a long time since I posted any article on my blog. Today presented an interesting scenario where I wanted to mock out a void method that accepted out parameters. The void method does not explicitly return anything but implicitly modify the parameters so there has to be a callback method attached.

Normally, with return methods you'd do something like:
mockObject.Setup(x => x.GetSomething(It.IsAny<string>)).Returns("Whatever");

But with a void method, we do not return anything but still don't want a NullReferenceException to be thrown. So we do something like:
mockObject.Setup(x => x.DoVoid(It.IsAny<object>)).Verifiable();

Please note that I am passing parameters in both methods above just to build up to the actual problem at hand.

So what if we want to pass out parameter? Can we do something like
It.IsAny<List<Person>>()

?

Nope. Ref and out parameters need to be initialized. That takes care of part of the problem.
var myList = new List<Person>();

//Arrange
mockObject.Setup(x => x.GetAllIdiots(out myList)).Returns(null);

Now, what if we have a void method and want to modify something within the method. After all, that's why we use the out and ref parameters.

So we add a callback method. Here's how to do it:
//initialize the out object
var myList = new List<Person>();

//Arrange
mockObject.Setup(x => x.DoVoid(out myList))
.Callback<(List<Person>)>((person) =>
{

//feel free to do whatever here..
});

There you go. Simple. Easy. The variable within the callback can be named anything.