【发布时间】:2016-06-03 20:09:31
【问题描述】:
我有一个非常大的 POCO 对象集合,其中包含我需要模拟的几个子属性...
在使用快速观看时,我看到了我想要的实体......
我正在寻找一种扩展方法或一种对其进行字符串化的方法,以便我可以去我的单元测试并在那里模拟它......有点:
var myPoco = new Poco {
//here goes whatever i get from my magic method
};
关于如何对给定对象的所有属性名称和值进行字符串化以便可以分配?
编辑 1:
我正在寻找类似的东西:
public static string StringFy(this object obj, string prefix)
{
string result = "";
obj.GetType().GetProperties().ToList().ForEach(i =>
{
result += prefix + "." + i.Name + " = ";
if (i.PropertyType == typeof(string))
{
result += "\"" + i.GetValue(obj) + "\";\r\n";
}
else
if (i.PropertyType == typeof(Guid))
{
result += "new Guid(\"" + i.GetValue(obj) + "\");\r\n";
}
else
{
var objAux = i.GetValue(obj);
result += (objAux == null ? "null" : objAux) + ";\r\n";
}
});
return result.Replace(" = True;", " = true;").Replace(" = False;", " = false;");
}
【问题讨论】:
-
我以前从来没有真正这样做过,所以我会把它作为评论而不是答案,但我认为你可以在你的类上创建一个索引器,使用反射通过字符串设置属性属性名称的值。使用反射查找以按属性名称设置值,如果您不熟悉我所说的内容,还可以查找索引器。
标签: c# unit-testing mocking poco