【问题标题】:Unit Testing using Microsoft Fakes - Skipping a function使用 Microsoft Fakes 进行单元测试 - 跳过函数
【发布时间】:2015-02-05 10:23:44
【问题描述】:

所以,我正在为我的项目编写单元测试用例。我被困在一个有 ref 参数的函数调用的地方。示例:-

public decimal addToSubtractFromCheckAmount(decimal dChkAmt,ref ICharge oCharge, bool blnAddTo, bool blnIncludeRBL)

我正在编写一个调用上述函数 (addToSubtractFromCheckAmount) 的函数的测试用例,我想跳过它并提供我的自定义返回值。

** 使用(ShimsContext.Create())

ShimClassName.AllInstances.addToSubtractFromCheckAmountDecimalIChargeBooleanBoolean
= (a, b, c, d, e) => new decimal(20);

** 这在我不传递 ref 参数时有效,但是当我给 ICharge 接口一个 ref 关键字时,该函数从我的单元测试用例类元数据中消失,并且当我构建项目时出现此错误 **

错误 101 Service.Fakes.ShimClassName.AllInstances' 不包含 定义为 'addToSubtractFromCheckAmountDecimalIChargeBooleanBoolean'

** 许多网站都在谈论具有字符串 ref 参数的 SHIMMING 函数,而不是接口、集合等。 例如

https://stackoverflow.com/questions/26918525/using-microsoft-fakes-to-shim-a-method-with-generic-list-parameters 这家伙的函数有 ref 参数,他是怎么拿到 AllInstances 里的函数的。

我在这个问题上停留了一段时间。有人可以帮忙吗?如果你们需要更多信息,请告诉我,谢谢。

【问题讨论】:

  • 方法名是驼峰式的。这是不好的做法。建议遵循 c# 代码约定。
  • 没关系,我在我的主要项目中遵循正确的编码实践。这只是测试项目中的一个测试用例。

标签: c# unit-testing ref microsoft-fakes shim


【解决方案1】:

如果您对使用 Fakes 不感兴趣,可以考虑使用 NSubstitute。我一直在我的 .NET 项目中愉快地使用 NSubstitute 和 Moq。它会是这样的:

//Create:
var chargeSubstitute= Substitute.For<ICharge>();

//Set a return value:
chargeSubstitute.DoSomething(whatever).Returns(resultYouWantToUseInTest);

现在您的测试可能如下所示:

var actual = something.addToSubtractFromCheckAmount(testValue,ref chargeSubstitute, true, true);

您可以根据您的预期值进行测试。见NSubstitueMoq

【讨论】:

  • 作为我公司的项目,我们无权使用除 Microsoft Fakes 之外的任何其他东西。真可惜。谢谢斯派克,你的回答看起来不错,但我认为我无法使用它。
【解决方案2】:

从我的测试来看,这似乎只有将 ref 参数移动到参数列表的末尾才有效。我用两个 int 参数之间的接口 ref 参数进行了测试,它没有出现在 AllInstances 属性中。但是,当我将 ref 参数移到末尾时,它出现了。

如果您这样做,您应该会看到一个名为 addToSubtractFromCheckAmountDecimalBooleanBooleanIChargeRef 的 shim 委托。

要记住的另一件事是,您不能将 ref 参数与 lambda 一起使用,因此您需要创建一个函数并将其分配给委托。像这样的:

decimal mockedFunction(ClassName instance, decimal dChkAmt, bool blnAddTo, bool blnIncludeRBL, ref ICharge oCharge)
{
    // ... assign oCharge?
    return 20m;
}

[TestMethod]
public void MyTest()
{
    using (ShimsContext.Create())
    {
        ShimClassName.AllInstances.addToSubtractFromCheckAmountDecimalBooleanBooleanIChargeRef
            = mockedFunction;

        // ...continue with test
    }
}

【讨论】:

    猜你喜欢
    • 2013-11-01
    • 2018-05-21
    • 2017-04-06
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2018-03-06
    相关资源
    最近更新 更多