Ninject: auto mocking using NSubstitute?

2019-07-04 00:24发布

问题:

Can anyone help, I am having problems using the auto-mocking that is available between Ninject and NSubstitute, actually the package is a ninject packaged called Ninject.MockingKernel.NSubstitute which should allow me to use Ninject to create mocks and return instances with mocks injected.

There seems to be a few examples for Moq and Rhinomocks but I don't see any for NSubstitute.

What I have so far is

this.kernel = new NSubstituteMockingKernel();  
var summaryService = this.kernel.GetMock<IMyService>(); // GetMock not available

Anybody using it?

回答1:

Here are a couple of examples adapted from the source code:

[TestFixture]
public class Tests
{
    /// <summary>
    /// Mocks are singletons.
    /// </summary>
    [Test]
    public void MocksAreSingletons()
    {
        using (var kernel = new NSubstituteMockingKernel())
        {
            var firstReference = kernel.Get<IDummyService>();
            var secondReference = kernel.Get<IDummyService>();

            firstReference.Should().BeSameAs(secondReference);
        }
    }

    /// <summary>
    /// Real objects are created for auto bindable types.
    /// </summary>
    [Test]
    public void RealObjectsAreCreatedForAutoBindableTypes()
    {
        using (var kernel = new NSubstituteMockingKernel())
        {
            var instance = kernel.Get<DummyClass>();

            instance.Should().NotBeNull();
        }
    }

    /// <summary>
    /// Reals objects are singletons.
    /// </summary>
    [Test]
    public void RealObjectsAreSingletons()
    {
        using (var kernel = new NSubstituteMockingKernel())
        {
            var instance1 = kernel.Get<DummyClass>();
            var instance2 = kernel.Get<DummyClass>();

            instance1.Should().BeSameAs(instance2);
        }
    }

    /// <summary>
    /// The injected dependencies are actually mocks.
    /// </summary>
    [Test]
    public void TheInjectedDependenciesAreMocks()
    {
        using (var kernel = new NSubstituteMockingKernel())
        {
            var instance = kernel.Get<DummyClass>();
            instance.DummyService.Do();

            instance.DummyService.Received().Do();
        }
    }

    public interface IDummyService
    {
        void Do();
    }

    public class DummyClass
    {
        public DummyClass(IDummyService dummyService)
        {
            this.DummyService = dummyService;
        }
        public IDummyService DummyService { get; set; }
    }
}