Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock a method of the subject under test in Moq?

Tags:

c#

mocking

moq

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?

like image 655
Antoine Avatar asked Jan 30 '14 15:01

Antoine


People also ask

How do you mock a method in Moq?

First, we instantiate the FakeDbArticleMock class and indicate which setup we want to use for this test. Then, it is necessary to instantiate the repository we want to test and inject the mock instance into it. Finally, we call the method we are testing and assert the results.

Can you mock a class with Moq?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces. However, there are a few limitations you should be aware of. The classes to be mocked can't be static or sealed, and the method being mocked should be marked as virtual.

What can be mocked with Moq?

Using Moq, you can mock out dependencies and make sure that you are testing the code in isolation. Moq is a mock object framework for .

How do you mock another method that is being tested in the same class?

We can mock runInGround(String location) method inside the PersonTest class as shown below. Instead of using mock(class) here we need to use Mockito. spy() to mock the same class we are testing. Then we can mock the method we want as follows.


1 Answers

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.

like image 198
dcastro Avatar answered Oct 25 '22 15:10

dcastro