Call Original
Use CallOriginal to make a specific mocked method or property execute its real implementation instead of mock behavior. This is the primary tool for partial mocking: override only the methods you need to fake and let everything else use real logic.
CallOriginal with Void Calls
You can use CallOriginal on methods and properties. This also includes methods that doesn't return a value. Consider the following class:
Sample setup
public class Log
{
public virtual void Info(string message)
{
throw new Exception(message);
}
}Let's arrange its Info method to be called with its original implementation and verify the call.
Example 1: Calling the original implementation
[TestMethod]
[ExpectedException(typeof(Exception))]
public void MockAssertOnCallOriginal()
{
// Arrange
var log = Mock.Create<Log>();
Mock.Arrange(() => log.Info(Arg.IsAny<string>())).CallOriginal();
// Act
log.Info("test");
}The call of the Info method throws an exception. To verify this behavior, we use the ExpectedException attribute provided from the Microsoft.VisualStudio.TestTools.UnitTesting namespace (found in Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll).
CallOriginal Depending on Parameter Value
This section shows how you can set up that a call to a method should call the original implementation for one argument and fake for another argument.
For this example, we will use the following sample class:
Sample setup
public class FooBase
{
public string GetString(string str)
{
return str;
}
}Example 2 shows how to implement the different behavior of the mocked object depending on the parameter value the method is invoked with.
Example 2: Calling original implementation vs customizing method behavior depending on the parameter value
[TestMethod]
public void ShouldCallOriginalForSpecificArgs()
{
// Arrange
// Create a mock of FooBase.
var foo = Mock.Create<FooBase>();
// Set up that the original method implementation should be called when the method is called with argument "x".
Mock.Arrange(() => foo.GetString("x")).CallOriginal();
// Set up that once the method is called with argument "y", it should return "z".
Mock.Arrange(() => foo.GetString("y")).Returns("z");
// Act
var actualX = string.Empty;
var actualY = string.Empty;
actualX = foo.GetString("x");
actualY = foo.GetString("y");
var expectedX = "x";
var expectedY = "z";
// Assert
Assert.AreEqual(expectedX, actualX);
Assert.AreEqual(expectedY, actualY);
}