[英]NSubstitute test works by itself, but throws Unexpected Matcher Argument in a suite
[英]NSubstitute - Argument matcher problem with ref / out
我想为MySubClass创建一个模拟。 但是,它的一种方法中具有参数ref 。 参数ref是MyReference类型的对象。 问题是:我不能使用相同的“ 参考 ” 参考我的课堂里面,这样的条件不被hitted。
var sub = Substitute.For<MySubClass>();
MyReference referenceForMockTest;
sub.MyMethod(Arg.Any<int>(), ref referenceForMockTest).Returns(x => { x[0] = new MyReference(); return true; });
CallerClass caller =new CallerClass();
caller.CallMySubClass();
有什么方法可以使用参数匹配器(或另一种方法)来解决它?
我可能需要类似以下代码的内容:
var sub = Substitute.For<MySubClass>();
MyReference reference;
sub.MyMethod(Arg.Any<int>(), ref Arg.Any<MyReference>()).Returns(x => { x[0] = new MyReference(); return true; });
我的课程非常接近:
class RootClass
{
MySubClass subclas = new MySubClass();
public void Process(int codeArg)
{
Response response = new Response();
response.code = 12;
//Create MySubClass using a some creational pattern
var MySubClass = createSubClass();
//I wanna mock it!
var isOk = MySubClass.MyMethod(codeArg, ref response);
if (!isOk)
{
throw new Exception();
}
}
}
class MySubClass
{
public bool MyMethod(int firstArg, ref Response response)
{
//Do something with firstArg and Response...
//If everything is Ok, return true
return true;
}
}
struct Response
{
public int code;
public String returnedMsg;
}
对于您显示的情况,我建议使用
.ReturnsForAnyArgs(x => ...)
。好消息是,NSubstitute的下一个发行版将获得您在第二个代码片段中显示的语法! :)(这样,该代码段将保持不变!)此功能当前位于https://github.com/nsubstitute/NSubstitute的存储库中,因此,如果您想尝试本地构建的NSubstitute,可以立即开始使用此功能。
这里还有一些使用out / ref参数的示例: https : //github.com/nsubstitute/NSubstitute/issues/459
因此,在这种情况下,例如:
MyReference referenceForMockTest;
sub.MyMethod(0, ref referenceForMockTest)
.ReturnsForAnyArgs(x => { x[0] = new MyReference(); return true; });
还要确保您要在类中替换的任何方法都是虚拟的,否则NSubstitute将无法使用它们。 有关替代类的更多信息,请参见创建替代品。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.