我如何validation一个方法被称为Moq一次?
我如何validation一个方法被称为Moq一次?  Verify()与Verifable()是非常混乱的。 
 您可以使用Times.Once()或Times.Exactly(1) : 
 mockContext.Verify(x => x.SaveChanges(), Times.Once()); mockContext.Verify(x => x.SaveChanges(), Times.Exactly(1)); 
以下是Times课程中的方法:
-   AtLeast– 指定一个嘲笑的方法应该被调用次数最less。
-   AtLeastOnce– 指定一个AtLeastOnce方法应该被调用一次。
-   AtMost– 指定一个AtMost方法应该被调用时间最大。
-   AtMostOnce– 指定应该最多调用一次模拟方法。
-   Between– 指定应该在from和to之间调用mocked方法。
-   Exactly– 指定一个模拟方法应该被调用准确的次数。
-   Never– 指定不应调用模拟方法。
-   Once– 指定应该一次调用模拟方法。
只要记住他们是方法调用; 我不断绊倒,认为他们是属性,忘记括号。
testing控制器可能是:
  public HttpResponseMessage DeleteCars(HttpRequestMessage request, int id) { Car item = _service.Get(id); if (item == null) { return request.CreateResponse(HttpStatusCode.NotFound); } _service.Remove(id); return request.CreateResponse(HttpStatusCode.OK); } 
而当DeleteCars方法用有效的id调用的话,那么我们可以validation一下,通过这个testing调用Service remove方法一次:
  [TestMethod] public void Delete_WhenInvokedWithValidId_ShouldBeCalledRevomeOnce() { //arange const int carid = 10; var car = new Car() { Id = carid, Year = 2001, Model = "TTT", Make = "CAR 1", Price=2000 }; mockCarService.Setup(x => x.Get(It.IsAny<int>())).Returns(car); var httpRequestMessage = new HttpRequestMessage(); httpRequestMessage.Properties[HttpPropertyKeys.HttpConfigurationKey] = new HttpConfiguration(); //act var result = carController.DeleteCar(httpRequestMessage, vechileId); //assert mockCarService.Verify(x => x.Remove(carid), Times.Exactly(1)); }