Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Moq to mock only some methods

Tags:

moq

I have the following method:

public CustomObect MyMethod() {     var lUser = GetCurrentUser();     if (lUser.HaveAccess)     {         //One behavior     }     else      {         //Other behavior     }      //return CustomObject } 

I want to mock IMyInterface.GetCurrentUser, so that while calling MyMethod I could get to one of the code paths to check it. How to do that with Moq?

I'm doing the following thing:

var moq = new Mock<IMyInterface>(); moq.Setup(x => x.GetCurrentUser()).Returns(lUnauthorizedUser);  //act var lResult = moq.Object.MyMethod(); 

But for some reason lResult is always null, and when I'm trying to get into MyMethod in debug, I'm always skipping to the next statement.

like image 714
Yaroslav Yakovlev Avatar asked Jan 22 '11 19:01

Yaroslav Yakovlev


People also ask

What can be mocked 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.

What is the difference between strict and loose mock?

When creating a mock, we can also give it strict or loose behavior. Strict behavior means that exceptions will be thrown if anything that was not set up on our interface is called. Loose behavior, on the other hand, does not throw exceptions in situations like this. Mocks, by default, are loose.

What is CallBase in Moq?

CallBase , when initialized during a mock construction, is used to specify whether the base class virtual implementation will be invoked for mocked dependencies if no setup is matched. The default value is false . This is useful when mocking HTML/web controls of the System.


1 Answers

This is called a partial mock, and the way I know to do it in Moq requires mocking the class rather than the interface and then setting the "Callbase" property on your mocked object to "true".

This will require making all the methods and properties of the class you are testing virtual. Assuming this isn't a problem, you can then write a test like this:

var mock = new Mock<YourTestClass>(); mock.CallBase = true; mock.Setup(x => x.GetCurrentUser()).Returns(lUnauthorizedUser); mockedTest.Object.MyMethod(); 
like image 95
lee Avatar answered Oct 10 '22 01:10

lee