Mug*_*gen 6 c# unit-testing ioc-container autofac vstest
我正在为我的 注册多种类型Container,实现各种接口。
以某种编程方式,我想要一个单元测试来检查所有解析是否成功,这意味着注册中没有循环或丢失的依赖项。
我试图添加这样的东西:
[TestMethod]
public void Resolve_CanResolveAllTypes()
{
foreach (var registration in _container.ComponentRegistry.Registrations)
{
var instance = _container.Resolve(registration.Activator.LimitType);
Assert.IsNotNull(instance);
}
}
Run Code Online (Sandbox Code Playgroud)
但是它在第一次运行时失败了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;
}
Run Code Online (Sandbox Code Playgroud)
GetType借自/sf/answers/826773251/
| 归档时间: |
|
| 查看次数: |
3287 次 |
| 最近记录: |