【发布时间】:2020-09-04 02:20:47
【问题描述】:
在这一点上我的大脑被炸了,如果这是一个愚蠢的,请道歉:
我正在尝试使用反射收集在运行时实现接口类型的所有类型,并让 AutoFixture 创建它们的实例。其中一些没有无参数的ctor。
结果,我正在做一个
public static IEnumerable<T> GetTypesWithInterface<T>() where T : class
{
var iType = typeof(T);
return iType.Assembly.GetLoadableTypes() //another method which does as it's namesake implies
.Where(type => iType.IsAssignableFrom(type) && !type.IsInterface)
.Select(t => FormatterServices.GetUninitializedObject(t) as T)
.ToList();
}
在其他地方使用以下代码调用代码:
protected List<T> AutoCreateSpecimenWithFixture<T>() where T : class
{
return TypeLoaderExtensions.GetTypesWithInterface<T>()
.Select(t => new SpecimenContext(Fixture).Resolve(t))
// .Select(t => Fixture.Create(t, specimen))
.Cast<T>()
.ToList();
}
在调用之前,我的 Fixture 是:
protected UnitTest()
{
Fixture = new Fixture();
Fixture.Customize(new AutoMoqCustomization());
CustomRegistrations();
}
private void CustomRegistrations()
{
_settingsServiceMock ??= Fixture.Freeze<Mock<ISettingsService>>();
Fixture.Register(() =>
new OverrideRule(_settingsServiceMock.Object));
}
我玩弄了上面的冻结/注入/注册,没有任何乐趣。在我的实际集成测试中,做:
var kek = Fixture.Create<OverrideRule>(); //works
_rules = AutoCreateSpecimenWithFixture<IRule>(); //throws no public ctor error :/
我也看过这些,但还没有按照AutoCreateSpecimenWithFixture 方法让它们工作:
AutoFixture: how to CreateAnonymous from a System.Type
AutoFixture: Unable to create an instance, probably no public constructor
任何帮助将不胜感激,谢谢。
【问题讨论】:
-
我认为问题在于您指定了一个接口(@987654328@)而不是一个类(
OverrideRule),并且您无法实例化一个接口,因此它会抛出该接口的错误没有公共构造函数。试试AutoCreateSpecimenWithFixture<OverrideRule>,然后你可以将它转换成你想要的任何东西(事件到你想要的界面) -
@MindSwipe AutoCreateSpecimenWithFixture 是以代码
return TypeLoaderExtensions.GetTypesWithInterface<T>()开头的方法的名称(我已经编辑了帖子以明确这一点)。因此,它应该具有 Fixture 应该尝试解决的三种具体类型(尽管一种没有无参数 ctor),因此我犹豫是否要进行更改
标签: c# .net moq xunit autofixture