using System;
using System.Reflection;
using System.Text;
namespace TestHelpers
{
/* Helper class for generating random values*/
public static class RandomHelper
{
/* This method can be used to fill all public properties of an object with random values depending on their type. CAUTION: it does not fill attributes that end with 'ID' or attributes which are called 'pk'. They have to be filled manually.*/
public static T FillPropertiesWithRandomValues<T>(T obj)
{
Type type = obj.GetType();
PropertyInfo[] infos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (PropertyInfo info in infos)
{
Type infoType = info.PropertyType;
if (info.CanWrite)
{
if (infoType.Equals(typeof(DateTime)) || infoType.Equals(typeof(DateTime?)))
info.SetValue(obj, RandomHelper.RandomDateTime(DateTime.Now, new DateTime(3000, 01, 01)), null);
else if (infoType.Equals(typeof(String)))
info.SetValue(obj, info.Name + " " + RandomHelper.RandomString(20, false), null);
else if ((infoType.Equals(typeof(long)) || infoType.Equals(typeof(double)) || infoType.Equals(typeof(Int32)) || infoType.Equals(typeof(Int64)) || infoType.Equals(typeof(int))) && !info.Name.ToLower().EndsWith("id") && !info.Name.ToLower().Equals("pk"))
info.SetValue(obj, RandomHelper.RandomNumber(0, 999999), null);
else if ((infoType.Equals(typeof(long?)) || infoType.Equals(typeof(double?)) || infoType.Equals(typeof(Int32?)) || infoType.Equals(typeof(Int64?)) || infoType.Equals(typeof(int?))) && !info.Name.ToLower().EndsWith("id") && !info.Name.ToLower().Equals("pk"))
{
Type genericType = info.PropertyType.GetGenericArguments()[0];
info.SetValue(obj, Convert.ChangeType(RandomHelper.RandomNumber(0, 999999), genericType), null);
}
else if (infoType.Equals(typeof(bool)))
info.SetValue(obj, RandomHelper.RandomBool(), null);
}
}
return obj;
}
private static Random randomSeed = new Random(); /* Generates a random string with the given length*/
public static string RandomString(int size, bool lowerCase)
{
StringBuilder RandStr = new StringBuilder(size);
/* Ascii start position (65 = A / 97 = a)*/
int Start = (lowerCase) ? 97 : 65;
/* Add random chars*/
for (int i = 0; i < size; i++)
RandStr.Append((char)(26 * randomSeed.NextDouble() + Start));
return RandStr.ToString();
}
public static int RandomNumber(int Minimal, int Maximal)
{
return randomSeed.Next(Minimal, Maximal);
}
/* Returns a random boolean value*/
public static bool RandomBool()
{
return (randomSeed.NextDouble() > 0.5);
} /* Returns a random color*/
public static DateTime RandomDateTime(DateTime min, DateTime max)
{
if (max <= min)
{
string message = "Max must be greater than min.";
throw new ArgumentException(message);
}
long minTicks = min.Ticks;
long maxTicks = max.Ticks;
double rn = (Convert.ToDouble(maxTicks) - Convert.ToDouble(minTicks)) * randomSeed.NextDouble() + Convert.ToDouble(minTicks); return new DateTime(Convert.ToInt64(rn));
}
}
}