74
如何验证一个方法与Moq恰好被调用一次? Verify()
与Verifable()
事情真的很混乱。如何验证一个方法与Moq完全调用一次?
如何验证一个方法与Moq恰好被调用一次? Verify()
与Verifable()
事情真的很混乱。如何验证一个方法与Moq完全调用一次?
您可以使用Times.Once()
,或Times.Exactly(1)
:
mockContext.Verify(x => x.SaveChanges(), Times.Once());
mockContext.Verify(x => x.SaveChanges(), Times.Exactly(1));
下面是对Times类的方法:
AtLeast
- 指定一个模拟的方法被调用倍为最低。AtLeastOnce
- 指定应将最少一次调用模拟方法一次。AtMost
- 指定一个模拟方法应该被调用时间最长。AtMostOnce
- 指定模拟方法应该最多调用一次。Between
- 指定应该在from和to之间调用mocked方法。Exactly
- 指定一个模拟方法应该被调用多次。Never
- 指定不应调用模拟方法。Once
- 指定应该一次调用模拟方法。只记得他们是方法调用;我不断绊倒,认为他们是属性,忘记了括号。
测试控制器可能是:
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方法,那么我们可以确认的是,通过这个测试,称为服务中删除方法恰好一次:
[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));
}
所以怎么办你得到/设置mockContext? – Choco 2017-11-09 04:18:28