C# 单元测试 XML 生成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/503784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unit testing XML Generation
提问by Dan
What unit testing strategies do people recommend for testing xml is being generated correctly.
人们推荐的用于测试 xml 的单元测试策略是正确生成的。
The my current tests seem abit primitive, something along the lines of:
我目前的测试似乎有点原始,大致如下:
[Test]
public void pseudo_test()
{
XmlDocument myDOC = new XmlDocument();
mydoc = _task.MyMethodToMakeXMLDoc();
Assert.AreEqual(myDoc.OuterXML(),"big string of XML")
}
回答by Vitor Silva
why not assume that some commercial xml parser is correct and validate your xml code against it? something like.
为什么不假设某些商业 xml 解析器是正确的并根据它验证您的 xml 代码?就像是。
Assert.IsTrue(myDoc.Xml.ParseOK)
other than that and if you want to be thorough I'd say you would have to build a parser yourself and validate each rule the xml specification requires.
除此之外,如果您想彻底了解,我会说您必须自己构建一个解析器并验证 xml 规范要求的每条规则。
回答by Mike K.
Another possibility might be to use XmlReader and check for an error count > 0. Something like this:
另一种可能性可能是使用 XmlReader 并检查错误计数 > 0。像这样:
void CheckXml()
{
string _xmlFile = "this.xml";
string _xsdFile = "schema.xsd";
StringCollection _xmlErrors = new StringCollection();
XmlReader reader = null;
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventHandler);
settings.ValidationType = ValidationType.Schema;
settings.IgnoreComments = chkIgnoreComments.Checked;
settings.IgnoreProcessingInstructions = chkIgnoreProcessingInstructions.Checked;
settings.IgnoreWhitespace = chkIgnoreWhiteSpace.Checked;
settings.Schemas.Add(null, XmlReader.Create(_xsdFile));
reader = XmlReader.Create(_xmlFile, settings);
while (reader.Read())
{
}
reader.Close();
Assert.AreEqual(_xmlErrors.Count,0);
}
void ValidationEventHandler(object sender, ValidationEventArgs args)
{
_xmlErrors.Add("<" + args.Severity + "> " + args.Message);
}
回答by Jeremy French
If you have a standard format that you expect the output to be, why not create an XML schema or DTD and validate against that. This won't depend on the data, so will be flexible. Also defining how the XML can be formed can be helpful when designing you system.
如果您有一个期望输出的标准格式,为什么不创建一个 XML 模式或 DTD 并对其进行验证。这将不依赖于数据,因此将是灵活的。在设计系统时,定义如何形成 XML 也很有帮助。
回答by svinto
Validate against XML schema or DTD, also check key that nodes have the values you expect.
根据 XML 模式或 DTD 进行验证,同时检查节点是否具有您期望的值。
回答by Adrian Zanescu
Validate it against an XSD schema using XmlSchema class. Its found under System.XML i think. Another option would be to write a serialization class (XMLSerializer) to deserialize your XML into an object. The gain will be that it will implicitly validate your structure and after that the values can be easily accessed for testing using the resulting object.
使用 XmlSchema 类根据 XSD 架构对其进行验证。我认为它是在 System.XML 下找到的。另一种选择是编写一个序列化类 (XMLSerializer) 来将您的 XML 反序列化为一个对象。好处是它将隐式验证您的结构,然后可以轻松访问这些值以使用结果对象进行测试。
回答by Robert Rossney
First, as pretty much everyone is saying, validate the XML if there's a schema defined for it. (If there's not, define one.)
首先,正如几乎每个人所说的那样,如果为 XML 定义了模式,则验证它。(如果没有,定义一个。)
But you can build tests that are a lot more granular than that by executing XPath queries against the document, e.g.:
但是您可以构建比通过对文档执行 XPath 查询更精细的测试,例如:
string xml="Your xml string here" ;
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
path = "/doc/element1[@id='key1']/element2[. = 'value2']";
Assert.IsTrue(doc.SelectSingleNode(path) != null);
This lets you test not only whether or not your document is semantically valid, but whether or not the method producing it is populating it with the values that you expect.
这让您不仅可以测试您的文档在语义上是否有效,还可以测试生成它的方法是否使用您期望的值填充它。
回答by merlinc
Another reason to use a Schema to validate against is that while XML nodes are explicitly ordered, XML attributes are not.
使用 Schema 进行验证的另一个原因是,虽然 XML 节点是明确排序的,但 XML 属性不是。
So your string comparison of:
所以你的字符串比较:
Assert.AreEqual(myDoc.OuterXML(),"big string of XML")
would fail if the attributes are in a different order, as could easily happen if one bit of XML was manually created and the other programatically.
如果属性的顺序不同,则将失败,如果手动创建 XML 位,而以编程方式创建另一位,则很容易发生这种情况。
回答by VoiceOfUnreason
Verify the resulting document is well formed Verify the resulting document is valid Verify the resulting document is correct.
验证生成的文档格式正确 验证生成的文档有效 验证生成的文档正确。
Presumably, you are crafting an XML document out of useful data, so you will want to ensure that you have the right coverage of inputs for your tests. The most common problems I see are
据推测,您正在用有用的数据制作一个 XML 文档,因此您需要确保您的测试输入正确覆盖。我看到的最常见的问题是
- Incorrectly escaped elements
- Incorrectly escaped attributes
- Incorrectly escaped element names
- Incorrectly escaped attribute names
- 错误转义的元素
- 错误转义的属性
- 错误转义的元素名称
- 错误转义的属性名称
So if you haven't already done so, you would need to review the XML spec to see what's allowed in each place.
因此,如果您还没有这样做,则需要查看 XML 规范以了解每个地方允许的内容。
How much "checking" should happen in each test isn't immediately clear. It will depend a lot on what a unit is in your problem space, I suppose. It seems reasonable that each unit test is checking that one piece of data is correctly expressed in the XML. In this case, I'm in agreement with Robert that a simple check that you find the right data at a single XPath location is best.
每次测试中应该进行多少“检查”尚不清楚。我想这在很大程度上取决于您的问题空间中的单位是什么。每个单元测试都在检查一段数据是否在 XML 中正确表达,这似乎是合理的。在这种情况下,我同意 Robert 的观点,即通过简单的检查在单个 XPath 位置找到正确的数据是最好的。
For larger automated tests, where you want to check the entire document, what I've found to be effective is to have an Expected results which is also a document, and walk through it node by node, using XPath expressions to find the corresponding node in the actual document, and then applying the correct comparison of the data encoded in the two nodes.
对于较大的自动化测试,您想要检查整个文档,我发现有效的是有一个预期结果,它也是一个文档,并逐个节点遍历它,使用 XPath 表达式找到相应的节点在实际文档中,然后应用两个节点中编码的数据的正确比较。
With this approach, you'll normally want to catch all failures at once, rather than aborting on first failure, so you may need to be tricksy about how you track where mismatches occurred.
使用这种方法,您通常希望一次捕获所有失败,而不是在第一次失败时中止,因此您可能需要在如何跟踪不匹配发生的位置方面变得棘手。
With a bit more work, you can recognize certain element types as being excused from a test (like a time stamp), or to validate that they are pointers to equivalent nodes, or... whatever sort of custom verification you want.
通过更多的工作,您可以将某些元素类型识别为从测试中免除的(例如时间戳),或者验证它们是否是指向等效节点的指针,或者……您想要的任何类型的自定义验证。
回答by Don Kirkby
This blog postby marianor gives a lightweight way to compare XElement structures, so I'm going to try that before tackling XMLUnit.
marianor 的这篇博文提供了一种比较 XElement 结构的轻量级方法,因此我将在处理XMLUnit之前尝试一下。
The first thing to do is normalize the two XMLs...using Linq... After both elements were normalized, simply you can compare both strings.
要做的第一件事是规范化两个 XML...使用 Linq...在规范化两个元素之后,您可以简单地比较两个字符串。
The XML is normalized by sorting the element and attribute names.
XML 通过对元素和属性名称进行排序来规范化。