开发者

Use reflection to Recreate Object for Test

I have a large number of C# WCF services that are being called by an enterprise system. When we encounter issues during development it can take a long time to reproduce the exact conditions on our development machines. Essentially we need to log the request using WCF & build an integration test based on the data logged. If the objects in the request are large this can take quite a bit of time.

I would like to be able to switch on logging/debug mode so that all the objects in the request are serialized into c# code. See method WriteCSharpToCreateObject. I would then be able to copy the code from the log directly into a new c# test. Here is my first effort - which kind of works for very simple objects. (The xml serilization does work) Is there any utility/library available that can do this?开发者_Go百科 Is there a better way?

private static void LogRequestParms(params object[] list)
{
    foreach (var o in list)
    {
        SerializeObjectAndWriteToFile(o);
        string cSharpCode = WriteCSharpToCreateObject(o);
    }
}

private static string WriteCSharpToCreateObject(object o)
{
    StringBuilder b = new StringBuilder();

    Type myType = o.GetType();
    b.AppendLine(myType.Name + " o = new " + myType.Name + "();");

    PropertyInfo[] myFields = myType.GetProperties();
    foreach (var v in myFields)
    {
        b.AppendLine("o." + v.Name + " = " + v.GetValue(o, null).ToString() + ";");
    }
    return b.ToString();
}

private static void SerializeObjectAndWriteToFile(object request)
{
    using (System.IO.Stream s = new System.IO.FileStream("C:\\temp\\logRequest.log", System.IO.FileMode.Append))
    {
        System.Xml.Serialization.XmlSerializer objectSerilizer = new System.Xml.Serialization.XmlSerializer(request.GetType());
        objectSerilizer.Serialize(s, request);
    }
}


You could also just serialize the objects coming in, and save them off in files (like you're already doing). Then in your test code, deserialize the objects from the files.


You could use binary serialization using the BinaryFormatter class and then deserialize the serialized objects in your tests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜