【问题标题】:How to Mock an Autofac Aggregate Service with Moq?如何使用 Moq 模拟 Autofac 聚合服务?
【发布时间】: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


    【解决方案1】:

    “我如何正确地模拟一个聚合服务,并提供行为 为它在单元测试期间?”

    尝试这样做(它不使用 automoq 只是一个起订量 :))

    var firstServiceImpl= new Mock<IFirstService>();
    var secondServiceImp2= new Mock<ISecondService>();
    
    var myAggregateServie= new Mock<IMyAggregateService>();
    
    myAggregateServie.SetupGet(x => x.FirstService ).Returns(firstServiceImpl);
    myAggregateServie.SetupGet(x => x.SecondService ).Returns(secondServiceImp2);
    .
    .
    .
    

    然后您可以模拟您的服务的行为,并验证调用,一些伪代码将如下所示。

    //Mock as above
    //Mock service behavior
    firstServiceImpl.Setup(m=>m.Method1()).Returns(1)
    
    //test method of you controller, lets assume that the method1 of controller 
    //is only calling firstService method named Method1()
    
    var result = SampleController.Method1(); 
    
    Assert.IsTrue( result == 1) 
    firstService.Verify(m=>m.Method1(), Times.Once()). 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 2012-03-18
      • 2010-10-19
      • 2016-09-30
      相关资源
      最近更新 更多