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()和其他方法。

相关内容

热门资讯

玩家科普!智星德州有脚本吗,a... 玩家科普!智星德州有脚本吗,aapoker透视脚本入口,可靠教程(有挂透视)1、玩家可以在aapok...
透视游戏!hh poker透视... 透视游戏!hh poker透视器下载(透视)切实真的是有挂(详细辅助科技教程);1、系统规律教程、辅...
我来向大家传授!德州私人局怎么... 我来向大家传授!德州私人局怎么透视,pokemmo手机脚本,系统教程(有挂方法)是一款可以让一直输的...
透视透视挂!拱趴大菠萝挂哪里(... 透视透视挂!拱趴大菠萝挂哪里(透视)真是存在有挂(详细辅助玩家教你)1、完成透视辅助安装,帮助玩家取...
玩家必看教程!htx矩阵wep... 玩家必看教程!htx矩阵wepoker辅助,epoker透视,透明挂教程(有挂透明)1、很好的工具软...
透视app!拱趴大菠萝万能挂(... 透视app!拱趴大菠萝万能挂(透视)一贯有挂(详细辅助实用技巧);1、金币登录送、破产送、升级送、活...
最新研发!hhpoker真的有... 1、最新研发!hhpoker真的有透视吗,hhpoker免费辅助器,必备教程(有挂攻略)。2、hhp...
透视数据!hhpoker作弊码... 透视数据!hhpoker作弊码怎么用(透视)一直是真的有挂(详细辅助解密教程)1、很好的工具软件,可...
免费测试版!wepoker私局... 免费测试版!wepoker私局代打,安装不了wepoker,科技教程(有挂攻略);致您一封信;亲爱w...
透视透视!wepoker分析(... 透视透视!wepoker分析(透视)竟然真的有挂(详细辅助靠谱教程);暗藏猫腻,小编详细说明原来是有...