Автофиксирование: как создавать полиморфные объекты с 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();
}
1 ответ
Решение
Нечто подобное должно работать:
public IX CreateSampleMessage(ISpecimenContext context)
{
var rm = this.types.ElementAt(this.random.Next(0, this.types.Length));
return (IX)context.Resolve(rm);
}
(Я не пытался скомпилировать и запустить репродукцию, поэтому, возможно, я где-то допустил ошибку.)