【Java Maven】XMLの差分チェック! XMLUnit2.xの導入手順とサンプルコード

こんにちは、飯塚です。
 
最近業務でデータの送受信にXMLを使用しますが、目視での確認は手間がかかるので他の方法を検討したくなりました。今回はXMLの差分チェックライブラリXMLUnit2.xをご紹介します。
 

記事の内容のサンプルプロジェクトはGitHubにあります。ご自由にお試しください。

XMLUnitとは

XMLUnitは、単純にXMLを文字列に変換するだけではXMLのテストは上手くいかないという理由で生まれたそうです。最も重要な特徴であるdiff-engineによってテスト観点に応じたテストコードを作成できます。
 
https://www.xmlunit.org

実行環境

OS
Windows 10
Java
Java SE 8
XMLUnit
2.6.3

XmlUnit2.Xの導入

今回はpom.xmlに「xmlunit-core」と「xmlunit-matchers」を追加するだけです。
pom.xml

	<!-- https://mvnrepository.com/artifact/org.xmlunit/xmlunit-core -->
	<dependency>
	  <groupId>org.xmlunit</groupId>
	  <artifactId>xmlunit-core</artifactId>
	  <version>2.6.3</version>
	</dependency>

	<!-- https://mvnrepository.com/artifact/org.xmlunit/xmlunit-matchers -->
	<dependency>
	  <groupId>org.xmlunit</groupId>
	  <artifactId>xmlunit-matchers</artifactId>
	  <version>2.6.3</version>
	</dependency>

https://mvnrepository.com/artifact/org.xmlunit/xmlunit-core
https://mvnrepository.com/artifact/org.xmlunit/xmlunit-matchers

サンプルコード

簡単なJUnitのサンプルコードです。
XmlUnitSample.java

package sample;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;

import org.junit.Test;
import org.xmlunit.builder.DiffBuilder;
import org.xmlunit.diff.Diff;
import org.xmlunit.diff.Difference;

public class XmlUnitSample {

    @Test
    public void testSame() {
    	assertEqualXml("src/test/xml/source.xml", "src/test/xml/comparison-same.xml");
    }

    @Test
    public void testDiff() {
    	assertEqualXml("src/test/xml/source.xml", "src/test/xml/comparison-diff.xml");
    }

    private void assertEqualXml(String sourcePath, String comparisonPath) {

		try {
		    FileInputStream source = new FileInputStream(sourcePath);
	        FileInputStream comparison = new FileInputStream(comparisonPath);

	        final Diff diff = DiffBuilder
	                .compare(source)
	                .withTest(comparison)
	                .build();

	        Iterator<Difference> iter = diff.getDifferences().iterator();
	        int size = 0;
	        while (iter.hasNext()) {
	            System.out.println(iter.next().toString());
	            size++;
	        }

	        assertThat(size, equalTo(0));

		} catch (FileNotFoundException e) {
			e.printStackTrace();

		}
	}
}

ポイントはDiffBuilderクラスです。DiffBuilderによってテスト観点に応じたテストコードを作成できます。例えば、「withNodeFilter()」を使用すれば特定のノードを除外して差分をチェックできます。
 
https://www.xmlunit.org/api/java/master/org/xmlunit/builder/DiffBuilder.html

実行結果(一致/差分あり)

実行結果(一致)
(実行:testSame(), 対象XML:source.xml, comparison-same.xml)

実行結果(差分あり)
(実行:testDiff(), 対象XML:source.xml, comparison-diff.xml)

まとめ

触ってみた感触は、導入はごく簡単でしかもテストコードもシンプルに書けるのでかなり使いやすい印象です。Java以外に.Netにも対応しており、今も開発が続いているようですので追加機能も期待できそうです。
 
一度使ってみてはいかがでしょうか。
 
 
 
 
《参考記事》

記事をシェア
MOST VIEWED ARTICLES