如何在调用扩展方法时用Moq模拟Autofaq接口 [英] How to mock Autofaq interface with Moq, when an extension method is called

查看:36
本文介绍了如何在调用扩展方法时用Moq模拟Autofaq接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#/Autofac/Moq:我有这个类:

public class MyService
{
    private readonly IlifetimeScope _scope;

    public MyService(ILifetimeScope scope)
    {
        _scope = scope;
    }

    public void DoWork()
    {
         var dbContext = _scope.Resolve<IDataContext>();
    }
}

这在运行时起作用。但是,我不能对其进行单元测试,因为我不能模拟Resolve()方法。它是一种扩展方法。

能够嘲笑它的最佳方式是什么?最明显的做法是将IDataContext注入构造函数中,而不是注入ILifetimeScope,但由于各种原因,我不能。

那么,是否可以改为注入Func?

public class MyService
{
    private readonly Func<IDataContext> _dbContext;

    public MyService(Func<IDataContext> dbContext)
    {
        _dbContext = dbContext;
    }

    public void DoWork()
    {
         var ctxt = _dbContext();
         // do stuff
    }
}

如下所示:我可以模拟它,但Autofac会找出如何将正确的参数注入ctor吗?或者有没有更好/更简单的方法来做到这一点?

推荐答案

这很不理想,但可以检查扩展方法的内部结构并模拟它进行的实际非扩展调用。显然,这是脆弱的,因为新版本的Autofac可能会破坏您的测试。

对我来说,以下是成功的(Autofac v4.X):

Mock<IComponentRegistry> componentRegistryMock = new Mock<IComponentRegistry>();
IComponentRegistry componentRegistry = componentRegistryMock.Object;
IComponentRegistration componentRegistration = new Mock<IComponentRegistration>().Object;

componentRegistryMock
    .Setup(x => x.TryGetRegistration(It.IsAny<Service>(), out componentRegistration))
    .Returns(true);

lifetimeScopeMock
    .Setup(x => x.ComponentRegistry)
    .Returns(componentRegistry);

lifetimeScopeMock
    .Setup(x => x.ResolveComponent(componentRegistration, It.IsAny<IEnumerable<Parameter>>()))
    .Returns(dataService);

这篇关于如何在调用扩展方法时用Moq模拟Autofaq接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆