Hi team I am new to moq and not able to understand concept of
CallBase = true;
var mock = new Mock<IFoo> { CallBase = true };
According to git hub :Invoke base class implementation if no expectation overrides the member
But I have below test case in which i am able to mock base class member without using CallBase = true
// Creating Base class.
public abstract class Car
{
public virtual bool IsValidSpeed()
{
///complex logic
///returnig false just to compile code
return false;
}
}
// Creating child class
public class Ferrari : Car
{
public int Speed { get; set; }
public void PrintSpeed(int speed)
{
if (IsValidSpeed())
{
Speed = speed;
}
}
}
Below writing test case. I am not setting property CallBase = true for my mock object
public void MoqPracticeTest2()
{
// var mock = new Mock<Ferrari>() { CallBase = true };
var mock = new Mock<Ferrari>(MockBehavior.Strict);
//Mocking Base class function
mock.Setup(x=>x.IsValidSpeed()).Returns(true);
//calling function which will call base function
mock.Object.PrintSpeed(100);
//calling Verify on mock object
mock.Verify(x => x.IsValidSpeed(), Times.Once);
Assert.AreEqual(mock.Object.Speed,100); //Doing Assert
}
still above test case is passing without setting callback property.
can some one please explain use of CallBase = true
here.
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.
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.
You don't need to set the CallBase
to true
, since you just want to verify that provided that IsValidSpeed()
returns true
, the speed of the Ferrari
object would be the one provided to the PrintSpeed
method.
So by declaring the following:
mock.Setup(x=>x.IsValidSpeed()).Returns(true);
you can simulate this specific scenario, without getting into the details on how IsValidSpeed
is implemented.
On the other hand, just try this. Remove the above line and set the CallBase
to true. This time you should note that the assertion would fail. This is due to the fact that the actual method would be called and the value of false
would be returned, as you have already mentioned in your post. Hence in this case the value of provided speed would not be assigned to Speed
.
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