首页 > 解决方案 > NSubstitute - ref / out 的参数匹配器问题

问题描述

我想为我的MySubClass创建一个模拟。但是,它的一个方法中有一个参数ref。参数refMyReference类型的对象。问题是:我不能在我的班级中使用相同的' reference ' ref ,所以条件没有被满足。

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

标签: c#nsubstitute

解决方案


来自NSubstitute 组的帖子

对于您展示的情况,我建议使用.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 将无法使用它们。有关替代类的更多信息,请参阅创建替代品。


推荐阅读