gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:05:00 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com