Skip to content

Verify an array parameter in Moq

by mstrid on March 13th, 2012

Recently I encountered a scenario where I wanted to write a unit test that verifies that a method on a mock (using Moq) was called with the correct array parameter. The problem was that the array was built dynamically in the method calling the object that was mocked so I couldn’t use a simple reference test like this:

byte[] expectedArray = new byte[] { 1, 2,3 };
mock.Verify(m => m.Method(expectedArray));

My first thought was CollectionAssert but I couldn’t fit this into the Moq Verify method.

So I started to play around with different LINQ expressions to be able to write a function that verifies the elements in the passed array against an expected array. The function I came up with is far from perfect (for example it is having trouble handling if the method was called multiple times with arrays of different lengths) but it does the work for me:

byte[] expectedArray = new byte[] { 1, 2,3 };
mock.Verify(m => m.Method(It.Is<byte[]>(a => a.Where((b, i) => b == expectedArray[i]).Count() == expectedArray.Length));

Basically what it does is to count how many element in the passed array that are equal to the corresponding element in the expected array and then checks that it is the same number as the number of expected elements.

This will find any element that does not match the expected array. It will most probably throw an exception if the passed array contains more elements than the expected array but it should be used within a unit test so I guess this is ok since the important thing is that the UT fail.

Comments are closed.