Imagine we are building a calculator with one method to add 2 integers. Let's imagine further that when calling the add method, it calls the print method once. Here is how we can verify this:
public interface IPrinter { void Print(int answer); } public class ConsolePrinter : IPrinter { public void Print(int answer) { Console.WriteLine("The answer is {0}.", answer); } } public class Calculator { private IPrinter printer; public Calculator(IPrinter printer) { this.printer = printer; } public void Add(int num1, int num2) { printer.Print(num1 + num2); } }
And here is the test itself with comments in the code for further clarification:
[TestClass] public class CalculatorTests { [TestMethod] public void WhenAddIsCalled__ItShouldCallPrint() { var iPrinterMock = new Mock<IPrinter>();
Note. By default, Moq drowns out all properties and methods as soon as you create a Mock object. Therefore, without even calling Setup , Moq has already IPrinter methods for IPrinter , so you can just call Verify . However, as a good practice, I always configure it because we may need to force the parameters to the method to meet certain expectations, or the return value from the method to match certain expectations or the number of calls to it.
CodingYoshi Apr 09 '18 at 19:41 2018-04-09 19:41
source share