【发布时间】:2022-01-21 02:51:54
【问题描述】:
我的CompositionRoot 静态类有一个测试夹具,它几乎只是枚举我的 Autofac IContainer 的服务并尝试实例化它们。如果它可以实例化它们,那就是测试通过。目标是确保我不会忘记向我的 Autofac 容器注册新接口。
但是,某些已注册的类型在其构造函数中使用不打算或不能在 Autofac 中注册的类型。例如,我有一个在其构造函数中采用string 的类。我将这个类注入我的代码库的方式是:
Func<string, ITypeThatRequiresAFactory>
这是我的测试夹具(使用 NUnit3 + FluentAssertions):
[TestFixture]
[Parallelizable(ParallelScope.All)]
public class CompositionRootTest
{
private sealed class ConcreteTypeEnumerator : IEnumerable
{
private readonly IContainer _container;
public ConcreteTypeEnumerator()
{
_container = CompositionRoot.Setup();
}
public IEnumerator GetEnumerator()
{
return _container.ComponentRegistry.Registrations
.SelectMany(x => x.Services)
.OfType<TypedService>()
.GetEnumerator();
}
}
[TestCaseSource(typeof(ConcreteTypeEnumerator))]
public void Service_should_be_instantiable(Service service)
{
using var container = CompositionRoot.Setup();
container.Invoking(c => c.ResolveService(service))
.Should().NotThrow()
.And.NotBeNull();
}
}
测试 Service_should_be_instantiable 在尝试实例化实现 ITypeThatRequiresAFactory 的服务时将失败,因为其构造函数中有 string 参数。
如何将我的测试夹具重构为:
- 表达明确测试类型的列表
- 排除在
Service_should_be_instantiable测试的类型列表之外 - 并且必须编写手动测试用例来验证它们是否可以解决(很可能使用特殊的案例复合类型,如
Func<>)?
目标是使用 Autofac 的隐式关系类型用于自动工厂 (Func<>) 以及以后可能的其他隐式关系 (如 Lazy<>),因此,例如,需要我显式注册手写工厂的解决方案是一个非首发。
【问题讨论】:
标签: c# unit-testing nunit autofac