单元测试中,模拟一个新对象

在单元测试中,会遇到有上百个属性的实体,而这些属性中,大多都是以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         }

 

这里并没有写出所有的类型,只需要根据自己的测试需要补充。

posted @ 2012-06-12 15:30  StanHome  阅读(672)  评论(1编辑  收藏  举报