How do I verify a method was called exactly once with Moq?

后端 未结 3 811
滥情空心
滥情空心 2020-12-08 03:21

How do I verify a method was called exactly once with Moq? The Verify() vs. Verifable() thing is really confusing.

3条回答
  •  天命终不由人
    2020-12-08 04:13

    Test controller may be :

      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);
        }
    

    And When DeleteCars method called with valid id, then we can verify that, Service remove method called exactly once by this test :

     [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())).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));
        }
    

提交回复
热议问题