If you see the following error:
NSubstitute.Exceptions.CouldNotSetReturnDueToNoLastCallException : Could not find a call to return from.
You are likely trying to mock a method on a class that is not virtual. If you read the whole message you will see something like the following:
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.
If you have access to the source code for the class you can add the virtual keyword to the method you are trying to stub:
public class MyDependency
{
public virtual string Get() //virtual!
{
return "This is my dependency";
}
}
Another - less likely - reason could be it is not abstract and you need to make it abstract:
public abstract class MyDependency
{
public abstract string Get();
}
NSubstitute can mock both abstract and virtual methods, the Get()
methods in the above can be mocked in the following way:
var myDepdendency = Substitute.For<MyDependency>();
myDepdendency.Get().Returns("Setting the return value");
If none of the above helps, you can check out my post here on how to mock or stub classes without an interface.
I hope this helps you, let me know in the comments down below if you need more guidance!