3

谁能帮忙,我在使用 Ninject 和 NSubstitute 之间可用的自动模拟时遇到问题,实际上该包是一个名为 ninject 的打包调用 Ninject.MockingKernel.NSubstitute,它应该允许我使用 Ninject 创建模拟并返回注入模拟的实例。

Moq 和 Rhinomocks 似乎有一些示例,但我没有看到 NSubstitute 的任何示例。

到目前为止我所拥有的是

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

有人用吗?

4

1 回答 1

5

以下是改编自源代码的几个示例:

[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; }
    }
}
于 2013-09-05T15:13:57.100 回答