Question

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?

Was it helpful?

Solution

See the answer here for an explanation of why async void test methods do not work in xUnit.

The solution is to give your test method an async Task signature.

async void functionality has been added ready for version 2.0 of xunit, see here for details.

OTHER TIPS

It turns out that the issue was that my test method was marked as async removing that causes it to work as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top