Issues with partial mock inside an another

24 views
Skip to first unread message

Bruno Silva

unread,
Nov 14, 2018, 10:24:50 AM11/14/18
to NSubstitute
Hi, 
I'm having problems using partial mock inside an another one, like in the example below:



public class ClassA
    {
        private ClassB mock = NSubstitute.Substitute.ForPartsOf<ClassB>();

        public ClassB PropertyA
        {
            get
            {
                return mock;
            }
        }
    }

public class ClassB
    {
        public virtual string PropertyB
        {
            get
            {
                throw new System.Exception("ERROR");
            }
            set
            {
                throw new System.Exception("ERROR");
            }
        }
    }

I wanna do something like below, but I got an exception. 
Is there something wrong that I'm doing?

ClasseA mock = NSubstitute.Substitute.ForPartsOf<ClasseA>();
mock
.PropertyA.PropertyB.Returns("My own return");

David Tchepak

unread,
Nov 15, 2018, 12:13:17 AM11/15/18
to nsubs...@googlegroups.com
Hello,

With NSubstitute 3.x we need to make sure the base method (which throws) is not called before setting the returns:

            var mock = Substitute.ForPartsOf<ClassA>();
            mock.PropertyA.When(x => { var _ = x.PropertyB; }).DoNotCallBase();
            mock.PropertyA.PropertyB.Returns("My own return");

This roughly translates to "when x.PropertyB getter is called, do not call the base method".

In the next version of NSubstitute this will be simplified to something like:

            var mock = Substitute.ForPartsOf<ClassA>();
            mock.PropertyA.Configure().PropertyB.Returns("My own return");

This should be available some time this month.

Hope this helps.
Regards,
David


--
You received this message because you are subscribed to the Google Groups "NSubstitute" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nsubstitute...@googlegroups.com.
To post to this group, send email to nsubs...@googlegroups.com.
Visit this group at https://groups.google.com/group/nsubstitute.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages