ninject / Ninject.MockingKernel

Extension for Ninject aiding testability in Moq, NSubstitute, and FakeItEasy
http://ninject.org/
Other
62 stars 25 forks source link

MockingKernel and Received throws an NotASubstituteException #31

Closed jeusdi closed 7 years ago

jeusdi commented 7 years ago

I'm using NSubstituteMockingKernel in order to build all my dependencies of my library classes. I've been struggling to solve a trouble for a week and I'm really exhausted. I need some help.

This is my class:

class Core : ICoreService, ICore {
    private ICoreConfiguration configuration;

    Core(ICoreconfiguration configuration) {
        this.configuration = configuration;
    }

    override ICoreService.ParentMethod() {   //ICoreService implementation
        foreach (Item item in this.configuration.Items)
            this.ChildMethod();
    }
    virtual ChildMethod() {
      //do something
    }
}

ICoreService is:

interface ICoreService {
    void ParentMethod();
}

ICore is:

interface ICore {
    ICoreConfiguration Configuration { get; }
}

ICoreConfiguration is:

interface ICoreConfiguration {
    IEnumerable<Item> Items { get; }
}

My test is:

[TestFixture]
public class UsersManagementTests
{
    private readonly NSubstituteMockingKernel IoCKernel;

    public UsersManagementTests()
    {
        this.IoCKernel = new NSubstituteMockingKernel();
    }

    [SetUp]
    public void SetUp()
    {
        this.IoCKernel.Reset();
    }

    [Test(Description = "Configured Users are well loaded on Kernel")]
    public void InitializationWithUsersTest()
    {
        //Setup Data
        Item item = Item.Create("item1");
        IEnumerable<Item> items = new List<Item>() { item };

        //Setup Mocks
        this.IoCKernel
            .Get<ICoreConfiguration>()
            .Items
                .Returns(items);
        Core core = this.IoCKernel.Get<Core>();

        //Act
        kernel.ParentMethod();

        //Assert
        IEnumerable<NSubstitute.Core.ICall> calls = kernel.ReceivedCalls(); // ((((((1))))))
        kernel.Received(1).ChildMethod();                                                    // ((((((2))))))
    }
}

When ((((((1)))))) or ((((((2)))))) are reached, I'm getting this NSubstitute.Exceptions.NotASubstituteException exception message now on last line:

NSubstitute extension methods like .Received() can only be called on objects created using Substitute.For() and related methods.

As you can see I'm trying to test ChildMethod method is reached once at least. ChildMethod must be called according to my Core.Kernel implementation.

I will really appreciate some help.

Thanks.

scott-xu commented 7 years ago

Please use GetMock to setup