Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 523
M. Ali Iftikhar Avatar asked Feb 08 '14 17:02

M. Ali Iftikhar


1 Answers

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.

like image 52
k.m Avatar answered Sep 21 '22 01:09

k.m