在单元测试中验证Autofac注册

时间:2017-07-16 10:52:34

标签: c# unit-testing autofac ioc-container vstest

我正在向我的Container注册多种类型,实现各种接口。

以某种程序化的方式,我希望有一个单元测试来检查所有解析是否成功,这意味着注册中没有循环或缺少依赖。

我尝试添加这样的内容:

        [TestMethod]
        public void Resolve_CanResolveAllTypes()
        {
            foreach (var registration in _container.ComponentRegistry.Registrations)
            {
                var instance = _container.Resolve(registration.Activator.LimitType);
                Assert.IsNotNull(instance);
            }
        }

但是在第一次运行解析Autofac.Core.Lifetime.LifetimeScope时它失败了,尽管我有接受ILifetimeScope作为参数的方法,并且在我的应用程序启动时就可以正常运行。

1 个答案:

答案 0 :(得分:2)

以下代码终于为我工作了:

private IContainer _container;

[TestMethod]
public void Resolve_CanResolveAllTypes()
{
    foreach (var componentRegistration in _container.ComponentRegistry.Registrations)
    {
        foreach (var registrationService in componentRegistration.Services)
        {
            var registeredTargetType = registrationService.Description;
            var type = GetType(registeredTargetType);
            if (type == null)
            {
                Assert.Fail($"Failed to parse type '{registeredTargetType}'");
            }
            var instance = _container.Resolve(type);
            Assert.IsNotNull(instance);
            Assert.IsInstanceOfType(instance, componentRegistration.Activator.LimitType);
        }
    }
}

private static Type GetType(string typeName)
{
    var type = Type.GetType(typeName);
    if (type != null)
    {
        return type;
    }
    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
    {
        type = assembly.GetType(typeName);
        if (type != null)
        {
            return type;
        }
    }
    return null;
}

GetType借鉴https://stackoverflow.com/a/11811046/1236401