Discussions

Ask a Question
Back to All

Verification of list parameters

I'm trying to verify a call was made to a repository AddRange method. I can verify the method was called at all like this:

GetMockFor<IThingRepository>()
    .Verify(x => x.AddRange(It.IsAny<IEnumerable<Thing>>()), Times.Once);

I can verify that it was passed the expected two objects using some of Moq's partial matching like this:

GetMockFor<IThingRepository>()
    .Verify(x => x.AddRange(It.Is<IEnumerable<Thing>>(y =>
        y.Count() == 2
            && y.Any(z => z.ThingType == ThingType.Foo)
            && y.Any(z => z.ThingType == ThingType.Bar))));

What I can't seem to do is get it to work using a more understandable partial matching syntax like this:

GetMockFor<IThingRepository>()
    .Verify(x => x.AddRange(Looks.Like(() => new[]
    {
        new Thing {ThingType = ThingType.Foo},
        new Thing {ThingType = ThingType.Bar},
    })));

In every case, the code runs but the verify fails saying the method was never called. I looked through the documentation examples, and while they cover the partial matching functionality, they don't have an example of partial matching a collection of things like this. I know the partial matching can do hierarchies, but what about collections?

I've even tried replacing the objects in the list with their own individual Looks.Likes:

GetMockFor<IThingRepository>()
    .Verify(x => x.AddRange(
        Looks.Like(() => new[]
        {
            Looks.Like(()=>new Thing {ThingType = ThingType.Foo}),
            Looks.Like(()=>new Thing {ThingType = ThingType.Bar}),
        })));

Because of the way this particular code is written, the order of the elements being added is predictable, so I've eliminated that variable, although a partial match that could ignore ordering would be pretty awesome.

What am I doing wrong here?