Ninject: auto mocking using NSubstitute?

梦想与她 提交于 2019-12-12 14:14:27

问题


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; }
    }
}


来源:https://stackoverflow.com/questions/18545983/ninject-auto-mocking-using-nsubstitute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!