33

I want to test method A of my class, but without calling the actual method B which is normally called by A. That's because B has a lot of external interactions I don't want to test for now.

I could create mocks for all the services called by B, but that's quite some work. I'd rather just mock B and make it return sample data.

Is that possible to do with Moq framework?

1 Answer 1

51

It is, with a catch! You have to make sure method B is virtual and can be overriden.

Then, set the mock to call the base methods whenever a setup is not provided. Then you setup B, but don't setup A. Because A was not setup, the actual implementation will be called.

var myClassMock = new Mock<MyClass>();
myClassMock.Setup(x => x.B()); //mock B

myClassMock.CallBase = true;

MyClass obj = myClassMock.Object;
obj.A(); // will call the actual implementation
obj.B(); // will call the mock implementation

Behinds the scenes, Moq will dynamically create a class that extends MyClass and overrides B.

7
  • 2
    Exactly, and it will be easiest if the virtual method B is either protected internal or public. Jan 30, 2014 at 15:56
  • Question: What does the line CallBase = true; do?
    – Hace
    Oct 20, 2016 at 9:33
  • 1
    @Hace If I recall correctly, it tells the mock object to call the methods defined in MyClass, unless an explicit setup is provided. If you did not call CallBase = true, then Moq would call a fake implementation of every virtual method, regardless of whether an explicit setup had been provided.
    – dcastro
    Oct 20, 2016 at 11:00
  • Hi, @dcastro Thanks I found out the CallBase line is indeed necessary to ensure the method is being called, thanks
    – Hace
    Oct 20, 2016 at 13:04
  • protected internal virtual does not show up on the mock setup?
    – Piotr Kula
    Nov 1, 2017 at 11:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.