Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq Match and Verify Array / IEnumerable parameters in method setup

I'm having problems verifying Ienumerable / Array type parameters when setting up expectation for methods call on my mock objects. I think since it's matching different references it doesn't consider it a match. I just want it to match the contents of the array, sometimes I don't even care about the order.

mockDataWriter.Setup(m => m.UpdateFiles(new string[]{"file2.txt","file1.txt"} ) );

Ideally I want something that works like the following, I could probably write an extension method to do this.

It.Contains(new string[]{"file2.txt","file1.txt"})

It.ContainsInOrder(new string[]{"file2.txt","file1.txt"})

The only built in way I can match these right now is with the predicate feature, but it seems this problem is common enough it should be built in.

Is there a built in way to match these types, or extension library I can use. If not I'll just write an extension method or something.

Thanks

like image 394
Ryu Avatar asked Aug 16 '09 20:08

Ryu


1 Answers

Previous answer by Oleg does not handle case where inputCollection has elements that are not in expectation.

For example:

MatchCollection(new [] { 1, 2, 3, 4 })

will match inputCollection { 1, 2, 3, 4, 5 } when it clearly shouldn't.

Here's the complete matcher:

public static IEnumerable<T> CollectionMatcher<T>(IEnumerable<T> expectation)
{
    return Match.Create((IEnumerable<T> inputCollection) =>
                        !expectation.Except(inputCollection).Any() &&
                        !inputCollection.Except(expectation).Any());
}
like image 92
AndyCunningham Avatar answered Sep 28 '22 03:09

AndyCunningham