Skip to content

Setting returnvalue to a substitute, previously configured in a AutoFixture.Register() call - throws CouldNotSetReturnDueToNoLastCallException #602

Closed
@MagnusMikkelsen

Description

@MagnusMikkelsen

Description
When setting the return value for a substitute method, where:

  • the metod has no arguments
  • the returnvalue also is a substitute
  • the returnvalue is configured in a AutoFixture.Register() call

the first Returns() method (foo.GiveMeBar().Returns(bar) in the example) throws a NSubstitute.Exceptions.CouldNotSetReturnDueToNoLastCallException.

It is possible to workaround the problem by either

  1. not configuring calls in the Register call block
  2. or by calling the method, that I want to set returnvalue for, before setting the returnvalue.

I have included these workarounds in the reproduction code as comments.

To Reproduce

using AutoFixture;
using AutoFixture.AutoNSubstitute;
using NSubstitute;

namespace ConsoleApp2
{
    public static class Program
    {
        public static void Main()
        {
            var f = new Fixture().Customize(new AutoNSubstituteCustomization() { ConfigureMembers = true });

            // Set default values for IBar
            f.Register<IBarRequest, IBar>(r =>
            {
                // Workaround 1:
                //Comment line below, and error goes away
                r.DefaultTrue.Returns(true);

                return (IBar)r;
            });

            // Create substitutes
            var foo = f.Create<IFoo>();
            var bar = f.Create<IBar>();


            // Doesn't throw:
            foo
                .GiveMeBarFromNumber(Arg.Any<int>())
                .Returns(bar);

            // Workaround 2:
            // Un-comment line below and error goes away
            // foo.GiveMeBar();

            // This Returns call throws CouldNotSetReturnDueToNoLastCallException
            foo
                .GiveMeBar()
                .Returns(bar);
        }
    }

    public interface IFoo
    {
        IBar GiveMeBar();
        IBar GiveMeBarFromNumber(int number);
    }

    public interface IBar
    {
        bool DefaultTrue { get; }
    }

    public interface IBarRequest : IBar { }
}

Expected behaviour
I did not expect any exception, because I called Returns() after calling my substitute, and I am not configuring other substitutes within Returns().

Environment:

  • NSubstitute version: 2.0.3
  • NSubstitute.Analyzers version: CSharp 1.0.11
  • AutoFixture 4.11.0
  • Platform: dotnetcore3.1 on Win. Also seen in .NET framework 4.8

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions