.net - moq用法 - test moq
我如何驗證一個方法被Moq調用一次? (2)
您可以使用Times.Once()
或Times.Exactly(1)
:
mockContext.Verify(x => x.SaveChanges(), Times.Once());
mockContext.Verify(x => x.SaveChanges(), Times.Exactly(1));
以下是Times課程中的方法:
-
AtLeast
- 指定一個嘲笑的方法應該被調用次數最少。 -
AtLeastOnce
- 指定應該最少調用一次AtLeastOnce
方法。 -
AtMost
- 指定一個AtMost
方法應該在最大時間內調用時間。 -
AtMostOnce
- 指定應該最多調用一次模擬方法。 -
Between
- 指定應該在from和to之間調用mocked方法。 -
Exactly
- 指定一個模擬方法應該被調用準確的次數。 -
Never
- 指定不應調用模擬方法。 -
Once
- 指定應該一次調用模擬方法。
請記住,他們是方法調用; 我不斷絆倒,認為他們是屬性,忘記了括號。
我如何驗證一個方法被Moq調用一次? Verify()
與Verifable()
是非常令人困惑的。
想像一下,我們正在用一種方法來構建一個計算器來添加2個整數。 讓我們進一步想像一下,要求在調用add方法時調用print方法一次。 以下是我們將如何測試這個:
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);
}
}
以下是在代碼中進行實際測試並進行進一步說明的代碼:
[TestClass]
public class CalculatorTests
{
[TestMethod]
public void WhenAddIsCalled__ItShouldCallPrint()
{
/* Arrange */
var iPrinterMock = new Mock<IPrinter>();
// Let's mock the method so when it is called, we handle it
iPrinterMock.Setup(x => x.Print(It.IsAny<int>()));
// Create the calculator and pass the mocked printer to it
var calculator = new Calculator(iPrinterMock.Object);
/* Act */
calculator.Add(1, 1);
/* Assert */
// Let's make sure that the calculator's Add method called printer.Print. Here we are making sure it is called once but this is optional
iPrinterMock.Verify(x => x.Print(It.IsAny<int>()), Times.Once);
// Or we can be more specific and ensure that Print was called with the correct parameter.
iPrinterMock.Verify(x => x.Print(3), Times.Once);
}
}