【问题标题】:Moq test passes even when verifying both Times.Once() and Times.Never() on same method call即使在同一方法调用中同时验证 Times.Once() 和 Times.Never() 时,最小起订量测试也会通过
【发布时间】:2013-12-13 13:26:48
【问题描述】:

我正在使用Xunit 来测试我的CarController 上的Create 方法,我正在使用Moq 来模拟我的CarRepository

然后我使用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 方法,所以我现在的问题是,如何在使用异步方法时验证方法被调用?

【问题讨论】:

    标签: c# asp.net unit-testing moq xunit.net


    【解决方案1】:

    请参阅答案 here,了解为什么 async void 测试方法在 xUnit 中不起作用。

    解决方案是给您的测试方法一个async Task 签名。

    async void 功能已添加到 xunit 2.0 版,详情请参阅here

    【讨论】:

      【解决方案2】:

      事实证明,问题在于我的测试方法被标记为 async 删除,导致它按预期工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-11
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-10
        相关资源
        最近更新 更多