C#-AutoFixture:如何使用ISpecimenBuilder创建多态对象
作者:互联网
我对如何更好地编写代码有些不知所措.使用反射来获得Create< T>.在标本的上下文是可怕的.遗憾的是,不赞成使用CreateAnonymous …所以我想不出更好的方法.
IX是一个接口,标本构建器正在创建用于实施IX的具体类的随机实例以进行测试.
/// <summary>
/// A specimen builder that creates random X messages.
/// </summary>
public class XMessageBuilder : ISpecimenBuilder
{
// for brevity assume this has types implementing IX
private readonly Type[] types;
private readonly Random random = new Random();
// THERE MUST BE A BETTER WAY TO DO THIS?
// CreateAnonymous is deprecated :-(
public IX CreateSampleMessage(ISpecimenContext context)
{
var rm = this.types.ElementAt(this.random.Next(0, this.types.Length));
var method = typeof(SpecimenFactory).GetMethod("Create", new[] { typeof(ISpecimenContext) });
var generic = method.MakeGenericMethod(rm);
var instance = generic.Invoke(null, new object[] { context });
return (IX)instance;
}
public object Create(object request, ISpecimenContext context)
{
var parameter = request as ParameterInfo;
if (parameter == null)
return new NoSpecimen();
if (parameter.ParameterType == typeof(IX))
return this.CreateSampleMessage(context);
if (parameter.ParameterType == typeof(IX[]))
{
var array = new IX[10];
for (int index = 0; index < array.Length; index++)
array[index] = this.CreateSampleMessage(context);
return array;
}
return new NoSpecimen();
}
解决方法:
这样的事情应该起作用:
public IX CreateSampleMessage(ISpecimenContext context)
{
var rm = this.types.ElementAt(this.random.Next(0, this.types.Length));
return (IX)context.Resolve(rm);
}
(不过,我没有尝试编译和运行repro,所以我可能在某个地方出错了.)
标签:autofixture,c 来源: https://codeday.me/bug/20191027/1947780.html