我正试图为失败的测试编写类似Nunit报告分析器/收集器之类的东西,并且在尝试反序列化测试报告时我被困住了。
非单位报告的结构如下:
<test-results ... >
<test-suite>
<results>
<test-suite> or <test-case> bunch of elements
<failure> // optional
</results>
</test-suite>
</test-results>因此,测试套件元素可以有其他测试套件元素的结果集合,也可以有测试用例元素的结果集合。由于测试套件具有与测试用例相同的属性,所以可以将其序列化为一个类型类:
[Serializable()]
public class TestResult
{
[XmlAttribute("name")]
public String Name { get; set; }
[XmlAttribute("executed")]
public String Executed { get; set; }
[XmlAttribute("success")]
public String Success { get; set; }
[XmlElement("failure", IsNullable = true)]
public Failure Failure { get; set; }
[XmlElement("results")]
public Results Results { get; set; }
[XmlAttribute("result")]
public String Result { get; set; }
[XmlAttribute("time")]
public String Time { get; set; }
[XmlAttribute("asserts")]
public String Asserts { get; set; }
}
[Serializable()]
public class TestCase : TestResult
{
}
[Serializable()]
public class TestSuite : TestResult
{
[XmlAttribute("type")]
public String Type { get; set; }
}结果类应该有一个测试套件或测试用例的列表:
[Serializable()]
public class Results
{
[XmlArray("results")]
[XmlArrayItem("test-case", Type = typeof(TestCase))]
[XmlArrayItem("test-suite", Type = typeof(TestSuite))]
public List<Result> Result { get; set; }
}在这里,TestCase和TestSuite是结果的空子类,因为arrtibutes和元素是相同的。没有从集合中以这种方式序列化的项。如果我试图为每个项目指定多个ArrauItem-s,而没有专用类型,那么解析者认为这是不合理的。
我如何能够使用不同但相关的元素来实际序列化集合?
发布于 2016-06-10 07:47:09
我相信下面的结构序列化到您想要的架构(删除了非必要的属性):
public class TestResult
{
...
[XmlElement("results")]
public TestResultsCollection Results { get; set; }
...
}
public class TestCase : TestResult
{
}
public class TestSuite : TestResult
{
[XmlAttribute("type")]
public String Type { get; set; }
}
[XmlRoot("test-results")]
public class TestResultsCollection
{
[XmlElement("test-case", Type = typeof(TestCase))]
[XmlElement("test-suite", Type = typeof(TestSuite))]
public List<TestResult> Results { get; set; }
}下面是我如何使用它来序列化/反序列化:
var serializer = new XmlSerializer(typeof (TestResultsCollection));
var testResultsCollection = new TestResultsCollection();
testResultsCollection.Items = new List<TestResult>
{
new TestSuite
{
Results = new TestResultsCollection
{
Items = new List<TestResult> {new TestCase(), new TestSuite()}
}
},
new TestCase
{
Results = new TestResultsCollection
{
Items = new List<TestResult> {new TestCase(), new TestSuite()}
}
}
};
using (var fileStream = File.CreateText("output.xml"))
{
serializer.Serialize(fileStream, testResultsCollection);
}
using (var fileStream = File.OpenText("output.xml"))
{
var deserialized = (TestResultsCollection)serializer.Deserialize(fileStream);
}https://stackoverflow.com/questions/37741756
复制相似问题