Reputation: 1587
I have a class with a method that has a signature like this:
public async Task<ResponseType> getSuff(string id,
string moreInfo,
deletegateName doStuff
) { // details. }
I am trying to mock this call with NSubstitute like this:
MyClass helper = Substitute.ForPartsOf<MyClass>();
ResponseType response = new ResponseType();
helper.getSuff(Arg.Any<string>(),
Arg.Any<string>(),
Arg.Any<DelegateDefn>()).Returns(Task.FromResult(response));
But I am getting a runtime error:
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);
The problem is, I think, the delegate. I just want to mock out the method, I do not want the delegate actually passed to be executed.
So, does anyone know how I can achieve this? Thanks.
Upvotes: 1
Views: 3350
Reputation: 7436
NSub works perfectly with delegates and async code. Here's a simple example:
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);
}
Please make sure that the method you specify is virtual or abstract. From the exception you got:
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.
Upvotes: 4