首页 > 解决方案 > 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)

标签: c#nsubstitute

解决方案


NSubstitute 不能拦截非虚拟类成员。(有关原因的解释,请参阅NSubstitute 的工作原理文档的非虚拟成员部分。)

尝试DoSomething声明为虚拟成员:

public class TestClass : ITestClass
{
    // ... other members elided ...

    public virtual string DoSomething()
    {
        return mOutput;
    }
}

NSubstitute.Analyzers包添加到您的测试项目中会发现非虚拟成员与 NSubstitute 一起使用的情况。


推荐阅读