![](/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.