Search code examples
c#unit-testingdictionarymoqverify

How to verify a Dictionary parameter?


I am using the Moq framework.

Given is the following code:

public interface ISomeInterface
{
    SomeResult DoWork( ISomeContainer foo, Dictionary<string, object> bar );
}

[ Test ]
public void SomeTest()
{
    Mock<ISomeInterface> mock = new Mock<ISomeInterface>();
    mock.Setup( m => m.DoWork( It.IsAny<ISomeContainer>(), It.IsAny<Dictionary<string, object>>() ) );

    new Cut( mock ).DoSomething();

    mock.Verify( m => m.DoWork( It.Is<ISomeContainer>( c => c.SomeValue == "foo" ), It.Is<Dictionary<string, object>>( d => ??? ) ) );
}

I know how to verify the properties of an interface parameter (ISomeContainer), but how is this possible with a Dictionary?

I would like to verify that the DoWork method is called with a simple Dictionary that contains only one key-value-pair KeyA + ValueA.


Solution

  • It.Is anticipates a delegate where the parameter is the current value and the return type bool.

    So, in your case: Func<Dictionary<string, object>, bool>

    In order to test your assumptions you can create the following helper method:

    private static bool AssertBar(Dictionary<string, object> bar)
    {
        Assert.Single(bar);
        Assert.Equal("KeyA", bar.Keys.Single());
        Assert.Equal("ValueA", bar.Values.Single());
        
        return true;
    }
    

    then you can call the Verify like this:

    mock.Verify(
     m => m.DoWork(
        It.Is<ISomeContainer>(c => AssertFoo(c)), 
        It.Is<Dictionary<string, object>>(d => AssertBar(d))),
     Times.Once);