AutoFixture的Without()方法在只有一个构造函数且所有参数都需要输入时无法正常使用?
创始人
2024-11-12 13:30:33
0

可以使用AutoFixture的Customize()方法,为该类型单独定制Fixture,从而解决该问题。具体代码示例如下:

public class TestClass { public string Name { get; set; } public int Age { get; set; }

public TestClass(string name, int age)
{
    Name = name;
    Age = age;
}

}

[TestMethod] public void TestCustomizedAutoFixture() { var fixture = new Fixture().Customize(new MultipleParameterConstructorCustomization()); var testClass = fixture.Create();

Assert.IsNull(testClass.Name);
Assert.AreEqual(0, testClass.Age);

}

public class MultipleParameterConstructorCustomization : ICustomization { public void Customize(IFixture fixture) { fixture.Customizations.Add(new MultipleParameterConstructorSpecimenBuilder()); } }

public class MultipleParameterConstructorSpecimenBuilder : ISpecimenBuilder { public object Create(object request, ISpecimenContext context) { var type = request as Type; if (type == null || type != typeof(T)) { return new NoSpecimen(); }

    var ctors = type.GetConstructors().Where(x => x.GetParameters().Count() > 1);
    if (!ctors.Any())
    {
        return new NoSpecimen();
    }

    return Activator.CreateInstance(type, ctors.First().GetParameters().Select(x => context.Resolve(x.ParameterType)).ToArray());
}

}

其中,MultipleParameterConstructorCustomization类为自定义类,用于定制fixture,重载ICustomization接口的Customize方法。MultipleParameterConstructorSpecimenBuilder类为自定义类,用于指定实例创建方式,重载ISpecimenBuilder接口的Create方法。对于只有一个构造函数但所有参数都需要输入的类型,可以通过这种方式自定义AutoFixture,来实现正常使用Without()和其他方法。

相关内容

热门资讯

解谜透视!impoker辅助,... 解谜透视!impoker辅助,微乐小程序自建房插件怎么安装,阶段教程(真的有挂)-哔哩哔哩1、很好的...
开挂透视!德州hhpoker是... 开挂透视!德州hhpoker是真的吗,微乐家乡小程序自建房辅助app,窍门教程(存在有挂)-哔哩哔哩...
分享透视!德州透视插件,微乐兰... 分享透视!德州透视插件,微乐兰州麻将小程序辅助,策略教程(真的有挂)-哔哩哔哩1、操作简单,无需德州...
关于透视!wpk有那种辅助吗,... 关于透视!wpk有那种辅助吗,微乐游戏小程序辅助器免费,手段教程(有挂技巧)-哔哩哔哩进入游戏-大厅...
关于透视!xpoker辅助神器... 关于透视!xpoker辅助神器,微信微乐小程序有窍门吗,攻略教程(有挂详情)-哔哩哔哩进入游戏-大厅...
解迷透视!菠萝辅助器免费版的特... 解迷透视!菠萝辅助器免费版的特点,微乐自建房怎么挂脚本,练习教程(有挂分享)-哔哩哔哩运菠萝辅助器免...
解迷透视!pokemmo脚本辅... 您好,pokemmo脚本辅助器这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
解迷透视!hhpoker作弊实... 解迷透视!hhpoker作弊实战视频,微乐a3纸牌有脚本,手段教程(有挂方法)-哔哩哔哩hhpoke...
教你透视!sohoo竞技联盟辅... 教你透视!sohoo竞技联盟辅助器,微乐贵阳麻将辅助,法门教程(有挂规律)-哔哩哔哩所有人都在同一条...
辅助透视!wepoker怎么看... 辅助透视!wepoker怎么看牌型,微乐家乡官方app,学习教程(确实有挂)-哔哩哔哩1、下载好we...