![](/img/trans.png)
[英]NSubstitute test works by itself, but throws Unexpected Matcher Argument in a suite
[英]NSubstitute - Argument matcher problem with ref / out
我想為MySubClass創建一個模擬。 但是,它的一種方法中具有參數ref 。 參數ref是MyReference類型的對象。 問題是:我不能使用相同的“ 參考 ” 參考我的課堂里面,這樣的條件不被hitted。
var sub = Substitute.For<MySubClass>();
MyReference referenceForMockTest;
sub.MyMethod(Arg.Any<int>(), ref referenceForMockTest).Returns(x => { x[0] = new MyReference(); return true; });
CallerClass caller =new CallerClass();
caller.CallMySubClass();
有什么方法可以使用參數匹配器(或另一種方法)來解決它?
我可能需要類似以下代碼的內容:
var sub = Substitute.For<MySubClass>();
MyReference reference;
sub.MyMethod(Arg.Any<int>(), ref Arg.Any<MyReference>()).Returns(x => { x[0] = new MyReference(); return true; });
我的課程非常接近:
class RootClass
{
MySubClass subclas = new MySubClass();
public void Process(int codeArg)
{
Response response = new Response();
response.code = 12;
//Create MySubClass using a some creational pattern
var MySubClass = createSubClass();
//I wanna mock it!
var isOk = MySubClass.MyMethod(codeArg, ref response);
if (!isOk)
{
throw new Exception();
}
}
}
class MySubClass
{
public bool MyMethod(int firstArg, ref Response response)
{
//Do something with firstArg and Response...
//If everything is Ok, return true
return true;
}
}
struct Response
{
public int code;
public String returnedMsg;
}
對於您顯示的情況,我建議使用
.ReturnsForAnyArgs(x => ...)
。好消息是,NSubstitute的下一個發行版將獲得您在第二個代碼片段中顯示的語法! :)(這樣,該代碼段將保持不變!)此功能當前位於https://github.com/nsubstitute/NSubstitute的存儲庫中,因此,如果您想嘗試本地構建的NSubstitute,可以立即開始使用此功能。
這里還有一些使用out / ref參數的示例: https : //github.com/nsubstitute/NSubstitute/issues/459
因此,在這種情況下,例如:
MyReference referenceForMockTest;
sub.MyMethod(0, ref referenceForMockTest)
.ReturnsForAnyArgs(x => { x[0] = new MyReference(); return true; });
還要確保您要在類中替換的任何方法都是虛擬的,否則NSubstitute將無法使用它們。 有關替代類的更多信息,請參見創建替代品。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.