NSubstitute:检查与数组参数获得方法 [英] NSubstitute: Checking received methods with array arguments

查看:150
本文介绍了NSubstitute:检查与数组参数获得方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证我的NSubstitute模拟的方法调用特定的阵列参数。

I want to verify that a method on my NSubstitute mock is called with a particular array argument.

说出接口, IProcessor ,有一个方法无效ProcessSomething(美孚[]东西])。说我的测试类被命名为指挥官。我建立了我的测试是这样的:

Say the interface, IProcessor, has a method void ProcessSomething(Foo[] something]). Say my class under test is named Commander. I set up my test like this:

//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



()接收通话失败:

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[]*)

所以,这看起来像ProcessSomething被称为比 FOOS ,对吧?

So this looks like ProcessSomething was called with some array other than foos, right?

好吧,如果我不是测试这个像,在这里我使用捕捉参数值 Arg.Do(),它成功:

Well, if I instead test this like, where I capture the argument value using Arg.Do(), it succeeds:

//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



所以捕捉参数,并(与NUnit的在这个例子中),它比较平等的工作,但在验证收到的呼叫失败。

So capturing the argument and comparing it for equality (with NUnit in this example) works, but verifying the received call fails.

这是在NSubstitute一个bug,还是我用错了?

Is this a bug in NSubstitute, or am I using it wrong?

推荐答案

我假设你的指挥官对象将接受的参数,并将它们放入一个数组,然后用它来调用处理器模拟。

I assume that your Commander object will take the arguments and puts them in an array which it then uses to call the Processor mock.

FOOS 变量是您创建一个另一个数组你的设置。即使它们具有相同的元件阵列不比较彼此相等。所以NSubstitute会抱怨说,它没有收到预期值(它接收到另一个阵列,它发生在包含相同的元素)

Your foos variable is another array which you create on your setup. Arrays don't compare equal to each other even if they have the same elements. So NSubstitute will complain that it didn't receive the expected value (it received another array which happened to contain the same elements).

编辑:试试这个版本:

//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));

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

这篇关于NSubstitute:检查与数组参数获得方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆