7

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.

M. Ali Iftikhar
  • 3,125
  • 2
  • 26
  • 36

1 Answers1

11

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.

k.m
  • 30,794
  • 10
  • 62
  • 86
  • sorry they are virtual. I just missed that in the example code above. I'll update my question now. – M. Ali Iftikhar Feb 08 '14 at 18:24
  • 1
    secondly, only setting calbase = true, doesn't works for me. I have tried that, it never calls the the actual implementation, unless i specifically set a method in setup as callbase. – M. Ali Iftikhar Feb 08 '14 at 18:27
  • If you're talking about `StartProcess` method it's because you're making setup on it explicitly. `CallBase = true` works for any method **not matched by explicit `Setup` call**. Remove `fakeService.Setup(m => m.StartProcess());` line and it should work. – k.m Feb 08 '14 at 19:04