方法设置中的Moq匹配和验证阵列/ IEnumerable参数

Ryu*_*Ryu 11 unit-testing moq mocking

在为我的模拟对象设置方法调用的期望时,我在验证Ienumerable/Array类型参数时遇到问题.我认为因为它匹配不同的引用它不认为它匹配.我只是希望它匹配数组的内容,有时我甚至不关心顺序.

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

理想情况下,我想要一些像下面这样的东西,我可能会写一个扩展方法来做到这一点.

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

It.ContainsInOrder(new string[]{"file2.txt","file1.txt"})
Run Code Online (Sandbox Code Playgroud)

我现在可以匹配的唯一内置方法是使用谓词功能,但似乎这个问题很常见,应该内置它.

是否有内置的方法来匹配这些类型,或我可以使用的扩展库.如果不是,我只会写一个扩展方法或其他东西.

谢谢

Ryu*_*Ryu 8

必须实现一些自定义匹配器,在版本3中没有找到任何其他内置方法来实现此目的.使用http://code.google.com/p/moq/wiki/QuickStart作为资源.

public T[] MatchCollection<T>(T[] expectation)
{
  return Match.Create<T[]>(inputCollection => (expectation.All((i) => inputCollection.Contains(i))));
}

public IEnumerable<T> MatchCollection<T>(IEnumerable<T> expectation)
{
  return Match.Create<IEnumerable<T>>(inputCollection => (expectation.All((i) => inputCollection.Contains(i))));
}


public void MyTest()
{

...

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

...


}
Run Code Online (Sandbox Code Playgroud)


小智 5

Oleg先前的回答无法处理其中inputCollection元素不在中的情况expectation

例如:

MatchCollection(new [] { 1, 2, 3, 4 })
Run Code Online (Sandbox Code Playgroud)

{ 1, 2, 3, 4, 5 }当显然不应该匹配inputCollection 时。

这是完整的匹配器:

public static IEnumerable<T> CollectionMatcher<T>(IEnumerable<T> expectation)
{
    return Match.Create((IEnumerable<T> inputCollection) =>
                        !expectation.Except(inputCollection).Any() &&
                        !inputCollection.Except(expectation).Any());
}
Run Code Online (Sandbox Code Playgroud)