XMLUnit - 比较两个 XML 响应



expectResponseXml 1:

<?xml version="1.0" encoding="UTF-8"?>
<GetResponse xmlns="http://whatever.co.uk/xsd/nam/message/GetResponse/">
    <Success>
        <Case>
            <Mort>M123456</Mort>
            <Appl>01</Appl>
        </Case>
        <Decision>D</Decision>
        <ProcessingRoute>R</ProcessingRoute>
        <Score>99999</Score>
    </Success>
</GetResponse>

和实际响应Xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<GetResponse xmlns:ns2="http://whatever.co.uk/xsd/nam/message/GetResponse/"> 
    <ns2:Success> 
        <ns2:Case> 
            <ns2:Mort>M123456</ns2:Mort> 
            <ns2:Appl>01</ns2:Appl> 
        </ns2:Case> 
        <ns2:Decision>D</ns2:Decision> 
        <ns2:ProcessingRoute>R</ns2:ProcessingRoute> 
        <ns2:Score>99999</ns2:Score> 
    </ns2:Success> 
</GetResponse>

错误消息是:

Expected child 'GetResponse' but was 'null' - comparing <GetResponse...> at /GetResponse[1] to <NULL>

比较代码:

Diff myDiffSimilar = DiffBuilder.compare(Input.fromString(actualResponseXml))
                                        .withTest(Input.fromString(expectedResponseXml))
                                        .checkForSimilar()
                                        .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName))
                                        .build();

我已经尝试了XMLUnit的官方github帐户中的所有内容以及几个类似的堆栈溢出问题来修复此错误,我认为这是命名空间的差异,应该被diffEngine忽略。从上面的代码中,我通过它们的字符串表示来比较两个 xml。当我取出checkForSimilar()时,我反而收到此错误

Expected namespace uri 'null' but was 'http://whatever.co.uk/xsd/nam/message/GetResponse/'

我的 maven 依赖项是

<dependency>
    <groupId>org.xmlunit</groupId>
    <artifactId>xmlunit-legacy</artifactId>
    <version>2.5.0</version>
    <scope>test</scope>
</dependency>

任何帮助将不胜感激!

在与上面那些人正确提到的问题是命名空间问题的问题作斗争之后,我发现了问题所在。将 jaxb 对象封送到 XML 时,请避免使用 QName(localPart( 构造函数,因为这会给不可预测的问题带来文档中已知和提到的问题!

在 XML 上下文中,所有元素和属性名称都存在于 命名空间的上下文。在施工过程中明确这一点 有助于防止难以诊断的 XML 有效性错误。这 构造函数 QName(String namespaceURI, String localPart( 和 QName(String namespaceURI, String localPart, String prefix( are 首选。链接在这里


为什么它对我来说是一个奇迹!!用

marshaller.marshal(new JAXBElement(new QName(namespaceURI, localPart, NS_PREFIX), jaxbObject.getClass(), jaxbObject), outputStream);

以删除不需要的命名空间并将其设置为默认值。

最新更新