c# - 即使在同一方法调用上验证 Times.Once() 和 Times.Never() 时,Moq 测试也会通过

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

我正在使用 Xunit测试 Create我的方法 CarController我正在使用 Moq mock 我的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方法,所以我现在的问题是,如何验证在使用异步方法时调用了方法?

最佳答案

查看答案here解释为什么 async void 测试方法在 xUnit 中不起作用。

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

async void 功能已添加到 xunit 2.0 版本中,参见 here了解详情。

关于c# - 即使在同一方法调用上验证 Times.Once() 和 Times.Never() 时,Moq 测试也会通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20567686/

相关文章:

c# - 另一个字符串未被识别为有效的日期时间和 XML 元素

c# - Quartz Scheduler (.Net) - 为什么在运行内置 'RescheduleJob' 方法后立即触发作业?

c# - 从 JSON.net 中的 JArray 获取值

asp.net - Bower ASP.NET Core MVC 缺少 jquery.validate.js 文件

java - AESCrypt 从 Java 到 C#

c# - 在 C# 中从分层数据集创建 XML

css - 如何控制文本框显示

java - Android - Activity 中方法的单元测试

java - 是否有自动测试 getter 和 setter 的 Java 单元测试框架?

java - 单元测试类的最佳实践,主要负责调用依赖项的方法,但也包含逻辑