2016-12-06 52 views
1

我有一類是有這樣的簽名的方法:如何處理委託參數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: Could not find a call to return from.

Make sure you called Returns() after calling your substitute (for example: mySub.SomeMethod().Returns(value)), and that you are not configuring other substitutes within Returns() (for example, avoid this: mySub.SomeMethod().Returns(ConfigOtherSub())).

If you substituted for a class rather than an interface, check that the call to your substitute was on a virtual/abstract member. Return values cannot be configured for non-virtual/non-abstract members.

Correct use: mySub.SomeMethod().Returns(returnValue);

Potentially problematic use: mySub.SomeMethod().Returns(ConfigOtherSub()); Instead try: var returnValue = ConfigOtherSub(); mySub.SomeMethod().Returns(returnValue);

問題是,我認爲,代表。我只是想嘲笑這個方法,我不想讓實際傳遞的委託被執行。

那麼,有沒有人知道我能做到這一點? 謝謝。

回答

2

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); 
} 

請確保您指定的方法是虛擬的或抽象的。從你得到的例外:

If you substituted for a class rather than an interface, check that the call to your substitute was on a virtual/abstract member. Return values cannot be configured for non-virtual/non-abstract members.

+0

謝謝,菜鳥的錯誤:我忘了讓方法虛擬:-( – dave