NSubstitute:当函数参数为 byte[]/class 时,为什么 mock 函数调用 returns null?
NSubstitute: Why does mock function call returns null when function parameter is byte[]/class?
我用 NSubstitute 创建了一个 Substitute
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
当我在测试中证明这个函数时,它们 return 值符合预期:
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 for specific args 文档中还有更多示例。
如果我们没有所需的确切参考,我们可以使用 argument matchers 来定义我们应该匹配的值:
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);
希望对您有所帮助。
我用 NSubstitute 创建了一个 Substitute
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
当我在测试中证明这个函数时,它们 return 值符合预期:
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 for specific args 文档中还有更多示例。
如果我们没有所需的确切参考,我们可以使用 argument matchers 来定义我们应该匹配的值:
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);
希望对您有所帮助。