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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With