One of our unit tests is to populate properties within our business objects with random data.
These properties are of different intrinsic types and therefore we would like to use the power of generics to return data of the type you pass in. Something along the lines of:
public static T GetData<T>()
How would you go about approaching this? Would a low level interface work? (IConvertible)
You could keep the "easy to use" GetData interface you've got there, but internally have a Dictionary<Type, object> where each value is a Func<T> for the relevant type. GetData would then have an implementation such as:
public static T GetData<T>()
{
object factory;
if (!factories.TryGet(typeof(T), out factory))
{
throw new ArgumentException("No factory for type " + typeof(T).Name);
}
Func<T> factoryFunc = (Func<T>) factory;
return factoryFunc();
}
You'd then set up the factory dictionary in a static initializer, with one delegate for each type of random data you wanted to create. In some cases you could use a simple lambda expression (e.g. for integers) and in some cases the delegate could point to a method doing more work (e.g. for strings).
You may wish to use my StaticRandom class for threads-safe RNG, by the way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With