NSubstitute
NSubstitute copied to clipboard
Use NSubstitute ForPartsOf API and call base class Virtual function
NSubstitute ver. 2.0.3 (This is old version) I need use old version . becuase my project not support c# 4.0 yet.
I want to use NSubstitute, ForPartsOf API , and I write a virtual method. but when I called virtual method , it thorw null NullReferenceException. like this:
public class NSubTest
{
public int GetVal()
{
return 1;
}
public virtual int VirtualGetVal()
{
return 1;
}
}
TEST:
NSubTest sub = Substitute.ForPartsOf<NSubTest>();
sub.GetVal();
sub.VirtualGetVal();//here get error:
ERROR:
NullReferenceException: Object reference not set to an instance of an object
Castle.Proxies.Invocations.NSubTest_VirtualGetVal.InvokeMethodOnTarget ()
Castle.DynamicProxy.AbstractInvocation.Proceed ()
NSubstitute.Proxies.CastleDynamicProxy.CastleInvocationMapper+<>c__DisplayClass1_0.<Map>b__0 ()
System.Lazy`1[System.Object].CreateValue ()
Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation.
I know if don't call by base method , it's be worked. like this :
sub.WhenForAnyArgs(x=>x.VirtualGetVal()).DoNotCallBase();
sub.VirtualGetVal().Returns(1);
"BUT" I need call base method when some case , How should I do ?
You probably need to specify your setup more specific. I cannot reproduce the problem.
I made a small project targeting the oldest .NET version supported by NSubstitute 2.0.3 (which is .NET Framework 3.5), added NSubstitute 2.0.3, copied your code and it works. (I dont get this NullReferenceException)