【发布时间】:2018-12-30 23:13:53
【问题描述】:
我在 .NET 4.6.2 上并通过 Nuget 使用以下版本的程序集:
服务
Autofac - 4.8.1
Autofac.Extras.AggregateService - 4.1.0
Autofac.Wcf - 4.1.0
Castle.Core - 4.3.1
测试
Autofac.Extras.Moq - 4.3.0
起订量 - 4.10.1
我为主机容器使用的设置与Docs 中的“入门”示例完全相同,您最终会得到一个从DynamicProxy 生成的代理,通过消除构造函数重载,这很有效。
在对使用这种注入类型的服务进行单元测试时,我似乎对如何正确模拟它感到困惑。
我花了几个小时尝试各种方法,但没有一个成功。这基本上是我所拥有的:
public interface IMyAggregateService
{
IFirstService FirstService { get; }
ISecondService SecondService { get; }
IThirdService ThirdService { get; }
IFourthService FourthService { get; }
}
public class SomeController
{
private readonly IMyAggregateService _aggregateService;
public SomeController(IMyAggregateService aggregateService)
{
_aggregateService = aggregateService;
}
}
using (var mock = AutoMock.GetLoose())
{
//var depends = mock.Mock<IMyAggregateService>().SetupAllProperties(); //Not working
//depends.SetupProperty(p => p.IFirstService, ?? );
//depends.SetupProperty(p => p.ISecondService, ?? );
//depends.SetupProperty(p => p.IThirdService, ?? );
//depends.SetupProperty(p => p.IFourthService, ?? );
var sut = mock.Create<SomeController>();
Action action = () => sut.SomeAction();
action.Should().xxxx
}
所以我遇到的第一个问题是IMyAggregateService 上没有设置器,所以SetupProperty 方法不起作用。当我使用SetupAllProperties 时,在运行时一切都是空的,所以这不起作用。我什至拉下了Autofac.Extras.AggregateService 代码并检查了Test 项目,但除了AggregateServiceGenerator 在某些时候可能有用之外,我真的无法从中得到任何帮助。
所以我的问题是,
“如何正确模拟聚合服务,并在单元测试期间为其提供行为?”
为了获得额外的荣誉,我还想知道如何提供作为属性的任何依赖项的特定实现,如下所示:
using (var mock = AutoMock.GetLoose())
{
mock.Provide<IFirstService>(this.MyImplProperty);
【问题讨论】:
标签: c# unit-testing moq autofac