2015-09-06 27 views
2

我使用XMLUnit比較下面的XML的XMLUnit測試預計數是真實的,但是是假

XML 1

<element1> 
</element1> 
<element2> Some Text </element2> 

XML 2

<element1/> 
<element2>Some Text</element2> 

我期待只有元素2進來的差異,但我得到這樣的區別element1

「子節點的預期存在爲真,但爲假」。
「預期數量的子節點1,但爲0」
「子節點‘#text’的預期存在,但爲空。

我知道這可以setIgnoreWhiteSpace走開,但我想element2空白差異。

+0

兩個元素的空白方面不同,有效的 - 你爲什麼會想到在element2表現出差異,但不部件1? –

回答

2

<element1/><element1></element1>應該返回相同的,但你有你的標籤之間的newline,所以這是一個1個或2個字符的文本節點(根據換行符是CR LF或只是LF)。

由於您沒有告訴解析器忽略空白,因此它會給出您在源數據中找到的所有內容。由您決定如何處理它。

-1

正如其他人提到的,XMLUnit將<element1>中的文本(由新行組成)視爲子節點。其他XML中的<element1>不是有任何子節點(甚至沒有空文本)。

如果你想忽略這樣的差異,你必須編寫自定義DifferenceListener

Diff diff = new Diff(doc1, doc2); 
diff.overrideDifferenceListener(new DifferenceListener() { 

    ... 

    @Override 
    public int differenceFound(Difference difference) { 
     if(difference.getId() == DifferenceConstants.HAS_CHILD_NODES_ID) { 
      Node controlNode = difference.getControlNodeDetail().getNode(); 
      Node testNode = difference.getTestNodeDetail().getNode(); 

      if(controlNode.getChildNodes().getLength() == 0) { 
       Node childNode = testNode.getChildNodes().item(0); 
       // note the trim method call 
       if(childNode.getNodeType() == Node.TEXT_NODE 
          && childNode.getTextContent().trim().isEmpty()) { 
        return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL; 
       } 
      } else { // we're sure the other node has children in the else part 
       Node childNode = controlNode.getChildNodes().item(0); 
       if(childNode.getNodeType() == Node.TEXT_NODE 
          && childNode.getTextContent().trim().isEmpty()) { 
        return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL; 
       } 
      } 
     } 
     return DifferenceListener.RETURN_ACCEPT_DIFFERENCE; 
    } 
}); 
+0

在這種情況下,沒有理由定製'DifferenceListener',只要告訴XMLUnit通過'XMLUnit.setIgnoreWhitespace(true)'來忽略元素內容空白。 –

+0

@StefanBodewig這也將忽略OP不想要的其他差異。 – manouti

+0

你是對的,我誤讀了要求 - 現在和Jon Skeet在一起。 –

相關問題