單元測試中,模擬一個新對象
在單元測試中,會遇到有上百個屬性的實體,而這些屬性中,大多都是以String Int32 等類型為主,而如果模擬這個實體,給這個實體賦隨機值,也要寫上百行代碼,效率極低
因此,我們可以通過反射來處理。
1 protected object CreateNewObject(object o, string instanceClassNames) 2 { 3 Guid guid = Guid.NewGuid(); 4 Random rd = new Random(); 5 int randomNum = rd.Next(); 6 7 Type type = o.GetType(); 8 PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); 9 foreach (PropertyInfo property in properties) 10 { 11 if (property.CanWrite == false) 12 { 13 //如果該屬性沒有可寫方法,退出當次循環 14 continue; 15 } 16 17 bool isDefaultCase = false; 18 switch (property.PropertyType.Name) 19 { 20 case "String": 21 property.SetValue(o, property.Name + guid.ToString(), null); 22 break; 23 case "Int32": 24 property.SetValue(o, randomNum, null); 25 break; 26 case "Boolean": 27 property.SetValue(o, true, null); 28 break; 29 case "DateTime": 30 property.SetValue(o, DateTime.Now, null); 31 break; 32 case "Guid": 33 property.SetValue(o, guid, null); 34 break; 35 default: 36 isDefaultCase = true; 37 break; 38 } 39 40 if (isDefaultCase 41 && !string.IsNullOrEmpty(instanceClassNames) 42 && !string.IsNullOrEmpty(property.PropertyType.Name) 43 && instanceClassNames.Contains(property.PropertyType.Name)) 44 { 45 // 如果是設置的自定義類型,遞歸模擬對象示例 46 object oSub = Assembly.Load("Strong.OnlineSchool.Entities").CreateInstance(property.PropertyType.FullName); 47 property.SetValue(o, CreateNewObject(oSub, instanceClassNames), null); 48 } 49 } 50 51 return o; 52 }
這里并沒有寫出所有的類型,只需要根據自己的測試需要補充。

浙公網安備 33010602011771號