c# - NSubstitute - ref / out 的参数匹配器问题
问题描述
我想为我的MySubClass创建一个模拟。但是,它的一个方法中有一个参数ref。参数ref是MyReference类型的对象。问题是:我不能在我的班级中使用相同的' 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;
}
解决方案
对于您展示的情况,我建议使用
.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 将无法使用它们。有关替代类的更多信息,请参阅创建替代品。
推荐阅读
- python - 如何将 JSON 中的系列扩展到列?
- android - 如何使用 Firebase 更新 Android 应用的 API 密钥、projectID 和 AppID?
- python - 使用 rasterio 重新采样栅格 - 网格间距的简单修改
- ros - 为什么机器人不能正确跟随路径?
- python - 如何将 HTML 链接到 python 脚本
- javascript - 如何正确使用此过滤器?
- jquery - 如何使用 jquery 编写 greentext 模块
- python - 表示任意分层数据的最佳数据结构是什么?
- javascript - 有没有办法克隆一个已经渲染的 React 组件,包括它的本地状态?
- python - 未安装模块“材料”