I'm using Xunit
to test the Create
method on my CarController
and I'm using Moq
to mock my CarRepository
.
I'm then using mockCarRepository.Verify(m => m.Create(It.IsAny<Car>()), Times.Once());
to check that the Create
method on my repository is being called. However the test passes irrespective of whether I call it or not.
Here is a complete example where I verify both that Create is called once AND that it is called never
. My test passes when I would have expected it to fail.
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
}
}
}
When I debug the test, although it still passes, I notice that the following exception is thrown:
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)
The exception is expected as I am calling Create
once and verifying Times.Never()
but I would like my test to fail. What do I need to do to achieve this?
Update It turns out that the problem was that I'd marked my test as async
- removing that causes it to pass. However the actual code I'm writing will call an async
method, so my question is now, how can I verify methods are called when using asynchronous methods?