c# - ForPartsOf 接听电话未显示
问题描述
出于测试目的,我想运行一个类的真正实现,但查看在其执行后调用它的函数。如果我正确理解了该文档,那就是ForPartsOf
它的用途。但是在使用它之后,它永远不会返回任何使用过的调用(虽然我知道它们会被断点触发)。
我创建了一个小程序来反映我的问题,最后我希望控制台输出告诉我两个实例都收到了 2 个调用。但“真正的”返回 0。
测试界面:
public interface ITestClass
{
string DoSomething();
}
测试类:
public class TestClass : ITestClass
{
private readonly string mOutput;
public TestClass(string output)
{
mOutput = output;
}
public string DoSomething()
{
return mOutput;
}
}
测试程序:
//using NSubstitute;
//using System;
//using System.Linq;
private const int cItterations = 2;
public void Run()
{
ITestClass mock = Substitute.For<ITestClass>();
mock.DoSomething().Returns("fake");
ITestClass real = Substitute.ForPartsOf<TestClass>("real");
RunCalls(mock); //fake, fake
Console.WriteLine();
RunCalls(real); //real, real
Console.WriteLine();
Console.WriteLine($"mock calls: {mock.ReceivedCalls().Count()}"); //mock calls: 2
Console.WriteLine($"real calls: {real.ReceivedCalls().Count()}"); //real calls: 0 (expected 2?)
}
private void RunCalls(ITestClass implementation)
{
for (int i = 0; i < cItterations; i++)
{
Console.WriteLine(implementation.DoSomething());
}
}
我很可能做错了什么,但我似乎无法弄清楚它是什么。任何帮助,将不胜感激。
使用:ms .net 4.7.2 和 NSubstitute 4.0.0(通过 nuget)
解决方案
NSubstitute 不能拦截非虚拟类成员。(有关原因的解释,请参阅NSubstitute 的工作原理文档的非虚拟成员部分。)
尝试DoSomething
声明为虚拟成员:
public class TestClass : ITestClass
{
// ... other members elided ...
public virtual string DoSomething()
{
return mOutput;
}
}
将NSubstitute.Analyzers包添加到您的测试项目中会发现非虚拟成员与 NSubstitute 一起使用的情况。
推荐阅读
- python - 从模板调用烧瓶函数时出现错误
- angular6 - 角度 6 中的“路由器”类型上不存在属性“getCurrentNavigation”
- php - 如何修复错误我没有收到请求的票证 ID
- python - Python,如何添加另一个装饰器来过滤现有多装饰器的输出与python中的属性?
- c# - 使用 for 循环进行选择排序的递归
- c# - 有没有办法覆盖 System.Data.SqlClient.SqlConnection?
- .htaccess - Htaccess 与 ip 列表禁止/重定向
- .htaccess - 更改 .htaccess 后网站关闭
- java - 从 iText7 中的表格中删除边框
- r - 如何根据多列中值之间的比率对数据进行子集化