NSubstitute:使用数组参数检查接收的方法

Jim*_*thy 39 c# nsubstitute

我想验证我的NSubstitute mock上的方法是否使用特定的数组参数调用.

说接口,IProcessor有一个方法void ProcessSomething(Foo[] something]).说我的课程被命名Commander.我设置了这样的测试:

//prepare
var processor = Substitute.For<IProcessor>;
var commander = new Commander(processor);
var foo1 = new Foo("alpha");
var foo2 = new Foo("bravo");
var foos = new [] {foo1, foo2};

//act
commander.DoSomething(foo1, foo2);

//verify
processor.Received().ProcessSomething(foos);  // FAILS
Run Code Online (Sandbox Code Playgroud)

Received()调用失败:

NSubstitute.Exceptions.ReceivedCallsException : Expected to receive a call matching:
    ProcessSomething(Foo[])
Actually received no matching calls.
Received 1 non-matching call (non-matching arguments indicated with '*' characters):
    ProcessSomething(*Foo[]*)
Run Code Online (Sandbox Code Playgroud)

所以这看起来像ProcessSomething被调用除了一些数组foos,对吧?

好吧,如果我改为测试这个,我在哪里捕获参数值Arg.Do(),它成功:

//prepare
//... as before
var actualFoos = null;

processor.ProcessSomething(Arg.Do<Foo[]>(x => actualFoos = x));

//act
commander.DoSomething(foo1, foo2);

//verify
Assert.That(actualFoos, Is.EqualTo(foos));   // SUCCEEDS
Run Code Online (Sandbox Code Playgroud)

因此,捕获参数并将其进行比较(在此示例中使用NUnit)可以正常工作,但验证接收的调用失败.

这是NSubstitute中的一个错误,还是我使用它错了?

aKz*_*enT 55

我假设你的Commander对象将接受参数并将它们放在一个数组中,然后用它来调用Processormock.

您的foos变量是您在设置中创建的另一个数组.即使阵列具有相同的元素,它们也不会相互比较.所以NSubstitute会抱怨它没有收到预期的值(它收到了另一个恰好包含相同元素的数组).

编辑:试试这个版本:

//prepare
var processor = Substitute.For<IProcessor>;
var commander = new Commander(processor);
var foo1 = new Foo("alpha");
var foo2 = new Foo("bravo");
var foos = new [] {foo1, foo2};

//act
commander.DoSomething(foo1, foo2);

//verify
processor.Received().ProcessSomething(Arg.Is<Foo[]>(foos2 => foos.SequenceEqual(foos2));
Run Code Online (Sandbox Code Playgroud)

这需要导入System.Linq命名空间