moq callbase用于不返回值的方法(void方法)

M. *_*har 5 tdd unit-testing moq mocking

我正在尝试模拟我正在测试的类,以便在测试它们时可以调用各个方法的基础.这将允许我仅将方法设置测试为callbase,并且将模拟在测试方法中调用的所有其他方法(同一类).

但是,我无法为不返回值的方法执行此操作.对于不返回值的方法,intellisense不显示callbase的选项.

这可能吗?

服务类:

public class Service
{
    public Service()
    {
    }

    public virtual void StartProcess()
    {
        //do some work
        string ref = GetReference(id);
        //do more work
        SendReport();
    }

    public virtual string GetReference(int id)
    {
        //...
    }

    public virtual void SendReport()
    {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

测试类设置:

var fakeService = new Mock<Service>();
fakeService.Setup(x => x.StartProcess());
fakeService.Setup(x => x.GetReference(It.IsAny<int>())).Returns(string.Empty);
fakeService.Setup(x => SendReport());
fakeService.CallBase = true;
Run Code Online (Sandbox Code Playgroud)

现在在我测试GetReference的测试方法中,我可以这样做:

fakeService.Setup(x => x.GetReference(It.IsAny<int>())).CallBase();
Run Code Online (Sandbox Code Playgroud)

但是当我想为StartProcess做同样的事情时,.CallBase就不存在了:

fakeService.Setup(x => x.StartProcess()).CallBase();
Run Code Online (Sandbox Code Playgroud)

一旦我使方法返回一些东西,这样一个布尔值,它就变得可用.

k.m*_*k.m 6

首先,你的模拟不起作用,因为Service类上的方法不是virtual.在这种情况下,Moq无法拦截调用以插入自己的模拟逻辑(详情请看这里).

设置mock.CallBase = true指示Moq委派任何与显式Setup调用不匹配的调用到其基本实现.删除fakeService.Setup(x => x.StartProcess());调用,以便Moq可以调用基本实现.