[英]AutoFixture: Freeze runtime type throws no public constructor error
My brain is fried at this point so apologies if this is a silly one:在这一点上,我的大脑被炸了,如果这是一个愚蠢的问题,我深表歉意:
I'm attempting to gather all types implementing an interface type at runtime using reflection and have AutoFixture create instances of them.我正在尝试使用反射收集在运行时实现接口类型的所有类型,并让 AutoFixture 创建它们的实例。 Some of them have no parameterless ctor.
其中一些没有无参数的ctor。
As a result, I'm doing a结果,我正在做一个
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();
}
And elsewhere calling the code with a:在其他地方使用以下代码调用代码:
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();
}
Before this is called, my Fixture is a:在调用此方法之前,我的 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));
}
I've toyed with Freeze/Inject/Register above, with no joy.我玩弄了上面的冻结/注入/注册,没有任何乐趣。 In my actual integration tests, doing:
在我的实际集成测试中,做:
var kek = Fixture.Create<OverrideRule>(); //works
_rules = AutoCreateSpecimenWithFixture<IRule>(); //throws no public ctor error :/
I've also looked at these but haven't gotten them to work yet as per the AutoCreateSpecimenWithFixture
method:我也看过这些,但还没有按照
AutoCreateSpecimenWithFixture
方法让它们工作:
AutoFixture: how to CreateAnonymous from a System.Type AutoFixture:如何从 System.Type 创建匿名
AutoFixture: Unable to create an instance, probably no public constructor AutoFixture:无法创建实例,可能没有公共构造函数
Any help would be appreciated please and thank you.任何帮助将不胜感激,谢谢。
I googled around some blogs and it looked like my seeds were being ignored, hence having to re-write my block to new up a seed as:我在一些博客上搜索了一下,看起来我的种子被忽略了,因此不得不重新编写我的块来新建一个种子:
return TypeLoaderExtensions.GetTypesWithInterface<T>()
.Select(t => new SpecimenContext(Fixture)
.Resolve(new SeededRequest(t, null)) as T)
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.