[英]Customizing AutoFixture to create specific type
I want to create customization for NLog's LogLevel type. 我想为NLog的LogLevel类型创建自定义。 Instances can be created by FromOrdinal static method. 实例可以通过FromOrdinal静态方法创建。
I want to restrict the ordinals used to create to the range (0..5). 我想将用于创建的序数限制为(0..5)。 Please mind, that I don't want to customize the entire fixture with the generator (as other integers might be bigger). 请注意,我不想使用生成器自定义整个灯具(因为其他整数可能更大)。
Here's the piece of code that I tried to use: 这是我尝试使用的代码:
class NLogCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<NLog.LogLevel>(
c => c.FromFactory(() =>
{
var ordinal = this.nlogOrdinalLevelFactory.Create<int>(); //Throws invalid cast exception
return NLog.LogLevel.FromOrdinal((int)ordinal);
}));
}
private readonly ISpecimenBuilder nlogOrdinalLevelFactory = new RandomNumericSequenceGenerator(0,5);
}
Unfortunately the code above throws InvalidCastException. 不幸的是,上面的代码抛出InvalidCastException。 What am I doing wrong in here? 我在这里做错了什么?
I'm using version 3.19.1. 我正在使用版本3.19.1。
To consume the RandomNumericSequenceGenerator and any other ISpecimenBuilder
directly, use the ISpecimenBuilder interface: 消耗RandomNumericSequenceGenerator和任何其他ISpecimenBuilder
直接使用ISpecimenBuilder接口:
object Create(object request, ISpecimenContext context);
In this example, instead of Create<T>
do: 在此示例中,代替Create<T>
执行:
fixture.Customize<LogLevel>(c => c.FromFactory(() =>
{
var ordinal = this.nlogOrdinalLevelFactory
.Create(typeof(int), new SpecimenContext(fixture));
return NLog.LogLevel.FromOrdinal((int)ordinal);
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.