我使用Xunit
來測試我的CarController
上的Create
方法,並且我使用Moq
來嘲笑我的CarRepository
。Moq測試即使在同一方法調用時同時驗證Times.Once()和Times.Never()
然後,我使用mockCarRepository.Verify(m => m.Create(It.IsAny<Car>()), Times.Once());
來檢查我的存儲庫上的Create
方法是否正在調用。然而,無論我是否打電話,測試都會通過。
這裏是一個完整的例子,我驗證both that Create is called once AND that it is called never
。當我預料到它失敗時,我的測試通過。
using System;
using Moq;
using Xunit;
namespace Test
{
public class CarTest
{
[Fact()]
public async void CreateTest()
{
var mockCarRepository = new Mock<CarRepository>();
var carController = new CarController(mockCarRepository.Object);
carController.Create(new Car
{
Make = "Aston Martin",
Model = "DB5"
});
mockCarRepository.Verify(m => m.Create(It.IsAny<Car>()), Times.Once());
mockCarRepository.Verify(m => m.Create(It.IsAny<Car>()), Times.Never());
}
}
public class CarController
{
private readonly CarRepository _repo;
public CarController(CarRepository repo)
{
_repo = repo;
}
public void Create(Car car)
{
_repo.Create(car);
}
}
public class Car
{
public virtual String Make { get; set; }
public virtual String Model { get; set; }
}
public class CarRepository
{
public virtual void Create(Car car)
{
// DO SOMETHING
}
}
}
當我調試測試,儘管它仍然推移,我發現以下異常被拋出:
A first chance exception of type 'Moq.MockException' occurred in Moq.dll
Additional information:
Expected invocation on the mock should never have been performed, but was 1 times: m => m.Create(It.IsAny<Car>())
No setups configured.
Performed invocations:
CarRepository.Create(Test.Car)
異常是預期的,因爲我打電話Create
一次驗證Times.Never()
但我會像我的測試失敗。我需要做什麼才能做到這一點?
更新事實證明,問題是我已將我的測試標記爲async
- 刪除導致它通過。然而,我正在寫的實際代碼將調用async
方法,所以我的問題是現在,如何驗證在使用異步方法時調用方法?