Add ReturnsSelf extension method?

39 views
Skip to first unread message

Meyrick Kirby

unread,
Oct 25, 2018, 12:08:46 AM10/25/18
to NSubstitute
If I have a simple interface as such:

public interface ISimple{
   
ISimple Do();
}

I can mock the Do method to return the mock using the Returns extension method:

ISimple simple = Substitute.For<ISimple>();
simple
.Do().Returns(simple);
ISimple act = simple.Do();
Equal(simple, act);

But it would be nice if I could simply call a ReturnsSelf extension method:

ISimple simple = Substitute.For<ISimple>();
simple
.Do().ReturnsSelf();
ISimple act = simple.Do();
Equal(simple, act);

David Tchepak

unread,
Oct 25, 2018, 1:26:20 AM10/25/18
to nsubs...@googlegroups.com
Hi!

Thank you for this suggestion! There is a problem implementing this because here the `ReturnsSelf()` extension method will not have a reference to self (`simple`). It will only get a reference to whatever `Do()` returns (in this case it will default to a new substitute).

We do have a different feature designed to help with these sort of builder patterns which you might be interested in instead. There is an extension called `ReturnsForAll<T>(T value)`, which will make all methods on a substitute that return `T` return the specific `value`. You will first need to bring this into scope with `using NSubstitute.Extensions;`. Here is an example:

using NSubstitute;
using NSubstitute.Extensions;
using NUnit.Framework;

namespace NSubTestWorkshop {
    public interface ISimple {
        ISimple Do();
    }

    [TestFixture]
    public class SampleTests {
        [Test]
        public void Sample() {
            var simple = Substitute.For<ISimple>();
            simple.ReturnsForAll<ISimple>(simple); // don't actually need the explicit generic here. I just added it for clarity
            var act = simple.Do();
            Assert.AreSame(simple, act);
        }
    }
}

Now any calls to `simple` that return an `ISimple` (if the interface had multiple builder-style methods) will return the self reference. You can override specific ones that need to behave differently using standard `.Returns()`.

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.

Meyrick Kirby

unread,
Oct 25, 2018, 4:01:44 AM10/25/18
to NSubstitute
David,

Thanks for the prompt reply.

I think that helps.

Meyrick
Reply all
Reply to author
Forward
0 new messages