Posted In: Hamcrest, Junit, Testing

How to unit test XML – JUnit + Hamcrest

Usecase – You need to unit test XML output and write multiple scenarios to test the data. Hamcrest library may be useful to achieve that

Hamcrest XPATH Matchers

Hamcrest 1.3

<dependency>
	<groupId>org.hamcrest</groupId>
	<artifactId>hamcrest-library</artifactId>
	<version>1.3</version>
	<scope>test</scope>
</dependency>

Classes used from Hamcrest

import org.hamcrest.xml.HasXPath

Using ErrorCollector so that execution continues even if assert statement fails.

package com.example.testing.hamcrest;

import static org.hamcrest.CoreMatchers.equalTo;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.hamcrest.xml.HasXPath;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.w3c.dom.Document;

public class TestHamcrestXml {

	@Rule
	public ErrorCollector collector = new ErrorCollector();

	@Test
	public void testNodeEquality1() {

		try {
			String xml = "<root><a><ab><ac>myval</ac></ab></a></root>";
			InputStream stream = new ByteArrayInputStream(xml.getBytes());
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
			        .newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(stream);
			doc.getDocumentElement().normalize();

			// positive -
			collector.checkThat(doc, HasXPath.hasXPath("/root/a/ab/ac"));

			// positive -
			collector.checkThat(doc, HasXPath.hasXPath("/root/a/ab/ac", equalTo("myval")));

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


	@Test
	public void testNodeEquality2() {

		try {
			String xml = "<root><a><ab><ac>myval1</ac><ac>myval2</ac><ac>myval3</ac></ab></a></root>";
			InputStream stream = new ByteArrayInputStream(xml.getBytes());
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
			        .newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(stream);
			doc.getDocumentElement().normalize();

			// positive -
			collector.checkThat(doc, HasXPath.hasXPath("/root/a/ab/ac[1]"));


			// positive -
			collector.checkThat(doc, HasXPath.hasXPath("/root/a/ab/ac[3]", equalTo("myval3")));

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

by , on August 17th, 2017

  • Categories