gpt4 book ai didi

c# - Ninject:使用 NSubstitute 自动模拟?

转载 作者:行者123 更新时间:2023-11-30 14:58:36 25 4
gpt4 key购买 nike

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

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

我目前的情况是

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

有人在用吗?

最佳答案

这里有几个例子改编自 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; }
}
}

关于c# - Ninject:使用 NSubstitute 自动模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18545983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com