The Moq test passes even when checking both Times.Once () and Times.Never () when calling the same method

I use Xunitto test a method Createon mine CarController, and I use Moqto mock mine CarRepository.

Then I use mockCarRepository.Verify(m => m.Create(It.IsAny<Car>()), Times.Once());to verify that the method Createin my repository is being called. However, the test passes regardless of whether I call it or not.

Here is a complete example where I check both that Create is called once AND that it is called never. My test passes when I 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)

, Create Times.Never(), , . ?

. , , async - , - . , , async, , ?

+4
2

. , async void xUnit.

, async Task.

async void ​​ 2.0 xunit, . .

+3

, , async , .

+2

All Articles