I am a little at a loss as to how to code this better. The use of reflection to obtain the Create<T>
on the specimen context is terrible. Sadly CreateAnonymous
is deprecated... So I can't think of a better way.
IX
is an interface, and the specimen builder is creating random instances of concrete classes implementing IX
for testing purposes.
/// <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();
}
Something like this ought to work:
public IX CreateSampleMessage(ISpecimenContext context)
{
var rm = this.types.ElementAt(this.random.Next(0, this.types.Length));
return (IX)context.Resolve(rm);
}
(I haven't tried to compile and run a repro, though, so I may have made an error somewhere.)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments