不返回值的方法的moq调用库(无效方法) [英] moq callbase for methods that do not return value (void methods)

查看:78
本文介绍了不返回值的方法的moq调用库(无效方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to mock my class that is under test, so that I can callbase on individual methods when testing them. This will allow me to test the method setup as callbase only, and all other methods (of the same class) called from within the test method will be mocked.

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

However, I am unable to do this for the methods that do not return a value. The intellisense just doesn't display the option of callbase, for methods that do not return value.

这可能吗?

服务类别:

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()
    {
        //...
    }
}

测试类设置:

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;

现在,在用于测试GetReference的测试方法中,我可以执行以下操作:

Now in my test method for testing GetReference I can do this:

fakeService.Setup(x => x.GetReference(It.IsAny<int>())).CallBase();

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

but when i want to do the same for StartProcess, .CallBase is just not there:

fakeService.Setup(x => x.StartProcess()).CallBase();

一旦我使该方法返回一些东西,例如布尔值,它就会变得可用.

it becomes available as soon as i make the method to return some thing, such a boolean value.

推荐答案

首先,由于Service类上的方法不是virtual,因此模拟无法正常工作.在这种情况下,Moq无法拦截插入其自己的模拟逻辑的调用(有关详细信息,请参见

First of all, your mock will not work because methods on Service class are not virtual. When this is a case, Moq cannot intercept calls to insert its own mocking logic (for details have a look here).

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

Setting mock.CallBase = true instructs Moq to delegate any call not matched by explicit Setup call to its base implementation. Remove the fakeService.Setup(x => x.StartProcess()); call so that Moq can call base implementation.

这篇关于不返回值的方法的moq调用库(无效方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆