【问题标题】:xUnit Moq setup failed to detect the method when a object is passed in传入对象时,xUnit Moq 设置未能检测到方法
【发布时间】:2020-05-06 05:48:43
【问题描述】:

我对单元测试和起订量非常陌生。在我的 .net core 3.1 项目中,我使用 xUnit 和 Moq 编写单元测试。我有以下情况,我无法弄清楚为什么起订量无法检测到我的功能。

我的单元测试配置如下,

        VASTest t = new VASTest()
        {
            RecurringAndOneOffChargeID = 2
        };

        _dataserviceMock.Setup(x => x.CreateVASBillingRunRecurringChargesTest(t))
            .ReturnsAsync(() => true);

        _dataserviceMock.Setup(x => x.CreateVASBillingRunRecurringChargesTest(2))
            .ReturnsAsync(() => true);  

在我的测试功能中,我尝试使用上述设置进行 moqup 的两个功能,

         var result1 = _VASBillingDataAccess.CreateVASBillingRunRecurringChargesTest(tvt).Result;
         var result2 = _VASBillingDataAccess.CreateVASBillingRunRecurringChargesTest(2).Result;

我的模型中有打击类,

public class VASTest
{
    public int RecurringAndOneOffChargeID { get; set; }
}

当我运行单元测试时,result1 始终为 false,但 result2 始终为 true。

您能否给我一些建议如何解决结果1?

谢谢。

【问题讨论】:

  • 如果我使用 IsAny 更改我的设置,我的结果 1 是正确的,但我实际上想根据我在单元测试中的设置验证 tvt 对象是否正确。 _dataserviceMock.Setup(x => x.CreateVASBillingRunRecurringChargesTest(It.IsAny())) .ReturnsAsync(() => true);

标签: unit-testing mocking moq xunit asp.net-core-3.1


【解决方案1】:

您的设置:

VASTest t = new VASTest()
{
  RecurringAndOneOffChargeID = 2
};

_dataserviceMock.Setup(x => x.CreateVASBillingRunRecurringChargesTest(t)).ReturnsAsync(() => true);

仅当 VASTest - t 的实例在 SUT 调用中使用时才有效,或者您为 VASTest 类实现自己的 equals 方法,如果 VASTest 的 2 个实例相等,则该方法可以解析对彼此。如果其中任何一个都不是这种情况,那么您将通过引用执行相等性检查,并且不会满足。您使用 int (2) 的其他设置作为 int 是一种值类型,并且始终对值本身进行相等性检查。

如果我没有实现IEquatable<T>,我会执行以下操作:

_dataserviceMock.Setup(x => 
    x.CreateVASBillingRunRecurringChargesTest(
        It.Is<VASTest>(t => t.RecurringAndOneOffChargeID.Equals(2))))
    .ReturnsAsync(() => true);

【讨论】:

  • 非常感谢您的支持。它现在正在工作
猜你喜欢
  • 2020-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多