在单元测试中验证Autofac注册
问题描述:
我正在向我的Container
注册许多类型,实现各种接口。在单元测试中验证Autofac注册
在一些编程方式中,我想要一个单元测试来检查所有解析是否成功,这意味着在注册中没有循环或缺失依赖关系。
我尝试添加像这样:
[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
作为参数的方法,并得到它就好了我的应用程序启动时。
答
下面的代码终于为我工作:
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://*.com/a/11811046/1236401
+0
请注意,如果您在多个实现中注册相同的接口(即使用'.AsImplementedInterfaces()',而许多类实现一些基本接口),则此测试将失败。 – Mugen
哪一行抛出异常借来的?抛出了什么确切的异常? – mjwills
'Resolve'行。问题是试图解决'LimitType'不正确,这种类型是解析的实例类型,而不是注册类型。 – Mugen