Mocking out method parameters in Moq

June 28, 2010 Waldemar Mękal

Recently I had a situation, when I was writing an unit test and I need to mock a method with an ‘out’ parameter. I had an import functionality where the import service was using a parser for processing input data before doing actual import. I wanted to test whether the import service handled errors from the parser. The parser interface was as below.

public interface IImportParser
{
  ImportRecord Parse(string data, out ErrorInfo[] errors);
}

I was using Moq for mocking, so I did a quick look to docs and I did the following.

var mock = new Mock(MockBehavior.Strict);

var errors = new ErrorInfo[]
{
  new ErrorInfo(3, "Parse error at line 3.")
};
mock
  .Setup(x => x.Parse(It.IsAny(), out errors))
  .Returns(new ImportRecord[]{ });

As you can see, mock was returning errors defined by me for any input for Parse() method, so it was what I looked for.

Hope this helps!

Latest posts