How to verify a Dictionary parameter?
Asked Answered
G

1

5

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.

Gatepost answered 9/4, 2021 at 6:8 Comment(0)
E
7

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);
Executory answered 9/4, 2021 at 7:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.