NSubstitute, out参数和条件返回
本文关键字:条件 返回 参数 out NSubstitute | 更新日期: 2023-09-27 18:19:16
我有一个场景与下面的场景没有什么不同,我想在NSubstitute中模拟…
public interface IGrabSomeData
{
bool GrabThatData(string filename, out byte[] data);
}
…有了这个接口,我希望它取一个文件名并检索字节数据。使用NSubstitute,我想传递特定的文件名并返回不同的或空的字节数组。通常我会通过在脚手架中指定参数并酌情使用'Returns'元素来实现此用法。不幸的是,我不能使用'Arg.Any()'参数,因为它会出现…
ref out参数必须是可赋值变量
…但如果我这样做,它始终是一个空字节数组。下面是使用上述界面的快速演示…
IGrabSomeData grabSomeData_1 = Substitute.For<IGrabSomeData>();
IGrabSomeData grabSomeData_2 = Substitute.For<IGrabSomeData>();
// Doesn't work
byte[] empty = { };
grabSomeData_1.GrabThatData(Arg.Any<string>(), out empty).Returns(x => { x[1] = new byte[] { 0, 1, 2 }; return true; });
byte[] test1 = {};
var result1 = grabSomeData_1.GrabThatData("" , out test1);
Assert.IsTrue( test1.length > 0); // FAILS
// Does work
grabSomeData_2.GrabThatData(Arg.Any<string>(), out empty).ReturnsForAnyArgs(x => { x[1] = new byte[] { 0, 1, 2 }; return true; });
byte[] test2 = { };
var result2 = grabSomeData_2.GrabThatData("", out test2);
Assert.IsTrue(empty.Length > 0); // Success!
简而言之,我需要声明'out'参数,但我必须为我的模拟调用分配一个变量-并且这不会在特定的'Returns'语句中得到识别。有没有可能实现像……
IGrabSomeData grabSomeData_1 = Substitute.For<IGrabSomeData>();
byte[] empty = { };
grabSomeData_1.GrabThatData("test1.xml", out empty).Returns(x => { x[1] = new byte[] { 0, 1, 2 }; return true; });
grabSomeData_1.GrabThatData("test2.xml", out empty).Returns(x => { x[1] = new byte[] { 0, 1, 2, 3, 4 }; return true; });
grabSomeData_1.GrabThatData("test3.xml", out empty).Returns(x => { x[1] = new byte[] { 0, 1 }; return true; });
byte[] test1 = {};
var result1 = grabSomeData_1.GrabThatData("test1.xml", out test1);
Assert.IsTrue(test1.Length == 2);
// etc.
提前感谢。
这没有经过测试,但也许您可以使用"Arg.Is<>",如下例所示:
IGrabSomeData grabSomeData_1 = Substitute.For<IGrabSomeData>();
byte[] empty = { };
grabSomeData_1.GrabThatData(Arg.Is<string>(x => string.Equals(x, "test1.xml")), out empty).Returns(x => { x[1] = new byte[] { 0, 1, 2 }; return true; });
grabSomeData_1.GrabThatData(Arg.Is<string>(x => string.Equals(x, "test2.xml")), out empty).Returns(x => { x[1] = new byte[] { 0, 1, 2, 3, 4 }; return true; });
grabSomeData_1.GrabThatData(Arg.Is<string>(x => string.Equals(x, "test3.xml")), out empty).Returns(x => { x[1] = new byte[] { 0, 1 }; return true; });
byte[] test1 = {};
var result1 = grabSomeData_1.GrabThatData("test1.xml", out test1);
Assert.IsTrue(test1.Length == 2);