2016-12-06 50 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