NSubstitute:当函数参数为byte[]/class时,为什么mock函数调用返回null



我用NSubstitute 创建了一个替换

var mockService = Substitute.For<IService>(); 

只有当函数参数为integer时,我才能成功地替换IService中的函数。在其他情况下,当我的代码调用IService的函数时,我会收到结果null/0/byte[0]

MyResponse Request(byte[] request, MyAddress target); //null
int test(int t); //expected result
int SimpleRequest(byte[] request, MyAddress target); /0
MyResponse SimpleParam(int i); //expected result
byte[] testbyte(byte[] t); //byte[0]
byte[] testintbyte(int t); //expected result
int testbyteint(byte[] t); //0

当我在测试中证明这个函数时,它们会按预期返回值:

Assert.Equal(mockService.Request(request, target), MyResponse);//true

为什么在NSubstitute中只能使用整数作为函数参数?

传递的byte[]似乎是一个不同的数组。它们可能具有相同的值,但却是不同的引用。

var testBytes = new byte[] { 0x1, 0x2, 0x3 };
mockService.testbyteint(testBytes).Returns(42);
Assert.Equal(mockService.testbyteInt(testBytes), 42);

该测试应该通过,因为testBytes值指向用于使用Returns存根调用以及断言中使用的实际调用的同一引用。Return中还有一些针对特定args文档的示例。

对于我们没有所需的确切引用的情况,我们可以使用参数匹配器来定义我们应该匹配的值:

var testBytes = new byte[] { 0x1, 0x2, 0x3 };
mockService.testbyteint(Arg.Is<byte[]>(bytes => bytes.SequenceEqual(new[] {0x1, 0x2, 0x3 })).Returns(42);
Assert.Equal(mockService.testbyteInt(testBytes), 42);

另一种选择是,当我们不介意得到哪个论点时,我们可以使用ReturnsForAnyArgs:

var testBytes = new byte[] { 0x1, 0x2, 0x3 };
mockService.testbyteint(null).ReturnsForAnyArgs(42);
Assert.Equal(mockService.testbyteInt(testBytes), 42);

希望这能有所帮助。

最新更新