NSubstitute,out参数和条件返回

时间:2013-06-21 10:42:27

标签: c# .net mocking nsubstitute

我有一个与我想在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.

提前致谢。

1 个答案:

答案 0 :(得分:0)

这未经过测试,但也许您可以使用“Arg.Is&lt;&gt;”,如下例所示:

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