moq callbase for methods that do not return value (void methods)

六月ゝ 毕业季﹏ 提交于 2019-12-10 15:11:02

问题


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.

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.

Is this possible?

The Service Class:

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

Test Class setup:

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;

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

fakeService.Setup(x => x.GetReference(It.IsAny<int>())).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.


回答1:


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).

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.



来源:https://stackoverflow.com/questions/21649279/moq-callbase-for-methods-that-do-not-return-value-void-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!