XmlUnit order based on value

时间:2016-04-04 16:29:41

标签: java xml xpath junit xmlunit

I am comparing a saved example xml with a live marshalled xml in my JUnit testing. Validating the presence of a key value pair in the xml.

I am making use of XmlUnit 2.1.0 specifically

My xml is as follows:

<entries>
        <entry>
            <key>delete</key>
            <value>ENABLED</value>
        </entry>
        <entry>
            <key>view</key>
            <value>DISABLED</value>
        </entry>
        <entry>
            <key>create</key>
            <value>DISABLED</value>
        </entry>
    </entries>

The order of the entries can vary. I'm unsure how to get it to validate correctly since it sees a different key value as a difference in the xml even though it's just an order change.

I am asserting similarity with the follow assertion in JUnit:

 assertThat(marshalledXml, isSimilarTo(Input.fromFile("path/to/example.xml").ignoreWhitespace().ignoreComments());

I suspect I may need to make use of XPath matchers or the DefaultNodeMatchers with an ElementSelector.

1 个答案:

答案 0 :(得分:1)

是的,您需要提供ElementSelector“知道”在特定情况下要选择哪些节点进行比较。

对于大多数文档,元素的名称似乎是您应该使用的。至少对entrieskeyvalue来说是如此。对于entry元素,您希望比较这些元素,这些元素在key元素中是直接子元素的匹配嵌套文本,对吗?

我认为这转化为

ElementSelectors.conditionalBuilder()
    .whenElementIsNamed("entry")
    .thenUse(ElementSelectors.byXPath("./key", ElementSelectors.byNameAndText))
    .elseUse(ElementSelectors.byName)
    .build();

有关ElementSelector选项的更详细讨论,请参阅https://github.com/xmlunit/user-guide/wiki/SelectingNodes。您的XML非常接近介绍中使用的table示例,并在下一节中进行了讨论。