Last active
March 6, 2018 21:43
-
-
Save pfrozi/53bc1bdfe12f5828f15f67cc7f8a16eb to your computer and use it in GitHub Desktop.
Creating mocks for all types of classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static object RandomString(int length) | |
{ | |
var random = new Random((int)DateTime.Now.Ticks); | |
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; | |
return new string( | |
Enumerable.Repeat(chars, length) | |
.Select(s => s[random.Next(s.Length)] | |
).ToArray() | |
); | |
} | |
private static int getRandom(int min, int max){ | |
return (new Random((int)DateTime.Now.Ticks).Next(min, max)); | |
} | |
private static T mockAll<T>() where T : new(){ | |
var mock = new T(); | |
foreach(var prop in typeof(T).GetProperties()){ | |
if(prop.PropertyType.Equals(typeof(string))) typeof(T).GetProperty(prop.Name).SetValue(mock, RandomString(1), null); | |
if(prop.PropertyType.Equals(typeof(decimal))) typeof(T).GetProperty(prop.Name).SetValue(mock, 0.0m, null); | |
if(prop.PropertyType.Equals(typeof(decimal?))) typeof(T).GetProperty(prop.Name).SetValue(mock, 0.1m, null); | |
if(prop.PropertyType.Equals(typeof(int))) typeof(T).GetProperty(prop.Name).SetValue(mock, 0, null); | |
if(prop.PropertyType.Equals(typeof(int?))) typeof(T).GetProperty(prop.Name).SetValue(mock, 1, null); | |
if(prop.PropertyType.Equals(typeof(double))) typeof(T).GetProperty(prop.Name).SetValue(mock, 0.0, null); | |
if(prop.PropertyType.Equals(typeof(double?))) typeof(T).GetProperty(prop.Name).SetValue(mock, 0.1, null); | |
} | |
return mock; | |
} | |
private static string ToJson(object obj) => | |
Newtonsoft.Json.JsonConvert.SerializeObject(obj); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment