Using moq to verify a call to a function with param parameters

c#, function, moq

Solution

mock.Verify( m => m.LogTrace( It.IsAny<string>(), It.IsAny<object[]>() ) );

The `params object[]` is passed to the method as `object[]` anyway so you just have to match the array somehow (as above for example, this accepts anything).

If you need more control over the list, use the `It.Is` matcher which allows you to create your own predicate:

 mock.Verify( m => m.LogTrace( It.IsAny<string>(),
            It.Is<object[]>(ps =>
                ps != null &&
                ps.Length == 1 &&
                ps[0] is int &&
                (int)ps[0] == 5
            ) ) );

This example shows how to verify if the param list is not empty and contains `5` as the only parameter of type `int`.

Problem

I have an ILogger interface with LogTrace(string value, params object[] parameters). Now I want to verify that the LogTrace is called and the string to log contains some id. The problem is that it can be called differently. E.g. 1) LogTrace("MyString " + id) 2) LogTrace("MyString {0}", id) and so on. Is there a good way with Moq to verify all the scenarios? I can only think of creating a hand-made mock that will format the string that will be available for verification.

Original source