从C#class hierachy生成模拟XML文件

时间:2016-04-26 09:01:45

标签: c# xml testing reflection

为了用XML生成UBL顺序文档,我使用Xml.Serialization在C#中创建了44个类。该类由根类" OrderType"组成。它包含许多属性(类),它们还包含更多属性。

为了测试类总是会构建一个将通过验证的XML文档。我想要一个XML文件,其中包含所有可能的节点(至少一次),类/属性的层次结构可以构建。

一个非常简化的代码示例:

[XmlRootAttribute]
[XmlTypeAttribute]
public class OrderType
{
     public DeliveryType Delivery { get; set; }
     //+ 50 more properties
     public OrderType(){}
}

[XmlTypeAttribute]
public class DeliveryType 
{
     public QuantityType Quantity { get; set; }
     //+ 10 more properties
     public DeliveryType (){}
}

我已经尝试在某些构造函数中初始化一些属性并且它工作正常,但这种方法需要一整周才能完成。

原来如此!有一个聪明的快速方法来生成一个Mock XML文档,其中所有属性都已初始化了吗?

外部节点只是被定义,例如:      <代码/>

1 个答案:

答案 0 :(得分:0)

嗯,有时你必须自己做:

using System;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;
namespace extanfjTest
{
    class Program
    {
        static void Main(string[] args)
        {
            OrderType ouo = new OrderType(DateTime.Now);
            SetProperty(ouo);
            XmlSerializer ser = new XmlSerializer(typeof(OrderType));
            FileStream fs = new FileStream("C:/Projects/group.xml", FileMode.Create);
            ser.Serialize(fs, ouo);
            fs.Close();
        }

        public static void SetProperty(object _object)
        {
            if (_object == null)
            { return; }
            foreach (PropertyInfo prop in _object.GetType().GetProperties())
            {
                if ("SemlerServices.OIOUBL.dll" != prop.PropertyType.Module.Name)
                { continue; }
                if (prop.PropertyType.IsArray)
                {
                    var instance = Activator.CreateInstance(prop.PropertyType.GetElementType());
                    Array _array = Array.CreateInstance(prop.PropertyType.GetElementType(), 1);
                    _array.SetValue(instance, 0);
                    prop.SetValue(_object, _array, null);
                    SetProperty(instance);
                }
                else
                {
                    var instance = Activator.CreateInstance(prop.PropertyType);
                    prop.SetValue(_object, instance, null);
                    SetProperty(instance);
                }
            }
        }
    }
}