NSubstitute icon indicating copy to clipboard operation
NSubstitute copied to clipboard

Use NSubstitute ForPartsOf API and call base class Virtual function

Open tim12332000 opened this issue 3 years ago • 1 comments

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 ?

tim12332000 avatar Aug 25 '22 09:08 tim12332000

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)

GeraldLx avatar Aug 25 '22 16:08 GeraldLx