![](/img/trans.png)
[英]How to raise a delegate event using a ref parameter in NSubstitute 3.1?
[英]How to handle delegate parameter in NSubstitute
我有一個類的方法具有這樣的簽名:
public async Task<ResponseType> getSuff(string id,
string moreInfo,
deletegateName doStuff
) { // details. }
我試圖像這樣用NSubstitute模擬此調用:
MyClass helper = Substitute.ForPartsOf<MyClass>();
ResponseType response = new ResponseType();
helper.getSuff(Arg.Any<string>(),
Arg.Any<string>(),
Arg.Any<DelegateDefn>()).Returns(Task.FromResult(response));
但是我遇到了運行時錯誤:
NSubstitute.Exceptions.CouldNotSetReturnDueToNoLastCallException:找不到從其返回的調用。
確保在調用替代項(例如:mySub.SomeMethod()。Returns(value))后調用了Returns(),並且確保沒有在Returns()中配置其他替代項(例如,避免這種情況:mySub.SomeMethod( )。返回(ConfigOtherSub()))。
如果您是用類而不是接口代替的,請檢查對替代者的調用是否在虛擬/抽象成員上。 不能為非虛擬/非抽象成員配置返回值。
正確使用:mySub.SomeMethod()。Returns(returnValue);
可能存在問題的用法:mySub.SomeMethod()。Returns(ConfigOtherSub()); 而是嘗試:var returnValue = ConfigOtherSub(); mySub.SomeMethod()。Returns(returnValue);
我認為問題是代表。 我只想模擬該方法,我不希望實際傳遞的委托被執行。
那么,有誰知道我如何實現這一目標? 謝謝。
NSub與委托和異步代碼完美配合。 這是一個簡單的例子:
public delegate void SomeDelegate();
public class Foo
{
public virtual async Task<int> MethodWithDelegate(string something, SomeDelegate d)
{
return await Task.FromResult(1);
}
}
[Test]
public void DelegateInArgument()
{
var sub = Substitute.For<Foo>();
sub.MethodWithDelegate("1", Arg.Any<SomeDelegate>()).Returns(1);
Assert.AreEqual(1, sub.MethodWithDelegate("1", () => {}).Result);
Assert.AreNotEqual(1, sub.MethodWithDelegate("2", () => {}).Result);
}
請確保您指定的方法是虛擬的或抽象的。 從異常中您得到:
如果您是用類而不是接口代替的,請檢查對替代者的調用是否在虛擬/抽象成員上。 不能為非虛擬/非抽象成員配置返回值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.