【问题标题】:AutoFixture: Freeze runtime type throws no public constructor errorAutoFixture:冻结运行时类型抛出公共构造函数错误
【发布时间】: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

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 我认为问题在于您指定了一个接口(@98​​7654328@)而不是一个类(OverrideRule),并且您无法实例化一个接口,因此它会抛出该接口的错误没有公共构造函数。试试AutoCreateSpecimenWithFixture&lt;OverrideRule&gt;,然后你可以将它转换成你想要的任何东西(事件到你想要的界面)
  • @MindSwipe AutoCreateSpecimenWithFixture 是以代码return TypeLoaderExtensions.GetTypesWithInterface&lt;T&gt;() 开头的方法的名称(我已经编辑了帖子以明确这一点)。因此,它应该具有 Fixture 应该尝试解决的三种具体类型(尽管一种没有无参数 ctor),因此我犹豫是否要进行更改

标签: c# .net moq xunit autofixture


【解决方案1】:

我用谷歌搜索了一些博客,看起来我的种子被忽略了,因此不得不重新编写我的块来新建一个种子:

return TypeLoaderExtensions.GetTypesWithInterface<T>()
    .Select(t => new SpecimenContext(Fixture)
        .Resolve(new SeededRequest(t, null)) as T)
    .ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    相关资源
    最近更新 更多