![](/img/trans.png)
[英]Need to create fakes for a class that manipulates the results of interface in microsoft unit testing tool using c#
[英]Unit Testing using Microsoft Fakes - Skipping a function
所以,这里我正在为我的项目编写单元测试用例。 我被困在有一个具有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'的定义
**许多网站都在谈论具有字符串引用参数的SHIMMING函数,但没有接口,Collections等参数。例如
https://stackoverflow.com/questions/26918525/using-microsoft-fakes-to-shim-a-method-with-generic-list-parameters当他的函数具有ref参数时,他如何在AllInstances中获得该函数。
我在这个问题上停留了一段时间。 有人可以帮忙吗? 如果您需要更多信息,请告诉我,谢谢。
如果您不习惯使用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);
您可以对照您的期望值进行测试。 参见NSubstitue或Moq
从我的测试来看,只有将ref参数移到参数列表的末尾,这看起来才有效。 我使用两个int参数之间的接口ref参数进行了测试,但未显示在AllInstances属性中。 但是,当我将ref参数移到末尾时,它出现了。
如果这样做,应该会看到一个名为addToSubtractFromCheckAmountDecimalBooleanBooleanIChargeRef
的垫片addToSubtractFromCheckAmountDecimalBooleanBooleanIChargeRef
。
要记住的另一件事是,您不能在lambda上使用ref参数,因此您需要创建一个函数并将其分配给委托。 像这样:
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.