gpt4 book ai didi

rhino-mocks - 自动模拟容器 : Rhino Mocks and NInject

转载 作者:行者123 更新时间:2023-12-04 13:55:47 27 4
gpt4 key购买 nike

有没有人有一个使用 Rhino Mocks 和 NInject 的自动模拟容器的实现?

最佳答案

好的,我使用 Moq 集成作为起点自己构建了一个。这很简单。你需要这 3 个类:

public class AutoMockingKernel : StandardKernel
{
private readonly IMockProvider _mockProvider;

public void Reset()
{
Components.Get<ICache>().Clear();
}

protected override bool HandleMissingBinding(Type service)
{
var isSelfBindable = TypeIsSelfBindable(service);

var binding = new Binding(service)
{
ProviderCallback = isSelfBindable
? StandardProvider.GetCreationCallback(service)
: _mockProvider.GetCreationCallback(),
IsImplicit = true
};

if (!isSelfBindable)
binding.ScopeCallback = ctx => null;

AddBinding(binding);

return true;
}

public AutoMockingKernel(IMockProvider mockProvider, INinjectSettings settings, params INinjectModule[] modules)
: base(settings, modules)
{
_mockProvider = mockProvider;
}

public AutoMockingKernel(IMockProvider mockProvider, params INinjectModule[] modules)
: base(modules)
{
_mockProvider = mockProvider;
}
}

internal class RhinoMockProvider : IProvider
{
public Type Type { get; private set; }

/// <summary>
/// Initializes a new instance of the <see cref="RhinoMockProvider"/> class.
/// </summary>
public RhinoMockProvider(Type type)
{
Type = type;
}

public object Create(IContext context)
{
return MockRepository.GenerateMock(Type, Type.EmptyTypes);
}
}

public class RhinoAutoMockProvider : IMockProvider
{
public Func<IContext, IProvider> GetCreationCallback()
{
return ctx => new RhinoMockProvider(ctx.Request.Service);
}
}

然后,您可以在单元测试中创建一个自动模拟内核,如下所示:
[Test]
public void Test()
{
var kernel = new AutoMockingKernel(new RhinoAutoMockProvider());
... etc
}

关于rhino-mocks - 自动模拟容器 : Rhino Mocks and NInject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1818302/

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