Skip to content

Instantly share code, notes, and snippets.

@simon04
Last active January 4, 2019 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simon04/d377c0a167f7112ddd2bfcbabfeee587 to your computer and use it in GitHub Desktop.
Save simon04/d377c0a167f7112ddd2bfcbabfeee587 to your computer and use it in GitHub Desktop.
Google Truth extension for XMLUnit

This provides a Google Truth extension for XMLUnit in order to allow to compare XML documents in unit tests.

XmlSubject.assertThat("<a><b foo='1' bar='2'></b></a>")
        .isTheSameXmlAs("<a><b bar='2' foo='1'/></a>");
import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
import org.w3c.dom.Document;
import org.xmlunit.builder.DiffBuilder;
import javax.xml.transform.Source;
import java.net.URL;
import static com.google.common.truth.Truth.assertAbout;
public final class XmlSubject extends Subject<XmlSubject, Object> {
private boolean ignoreWhitespace;
private XmlSubject(FailureMetadata metadata, @NullableDecl Object actual) {
super(metadata, actual);
}
public XmlSubject ignoreWhitespace() {
ignoreWhitespace = true;
return this;
}
private void isTheSameXmlAs(Object expected) {
final DiffBuilder builder = DiffBuilder.compare(expected).withTest(actual());
if (ignoreWhitespace) {
builder.ignoreWhitespace();
}
check("XML differences")
.that(builder.build().getDifferences())
.isEmpty();
}
private static XmlSubject assertThat(Object actual) {
return assertAbout(XmlSubject::new).that(actual);
}
public void isTheSameXmlAs(Source expected) {
isTheSameXmlAs((Object) expected);
}
public static XmlSubject assertThat(Source actual) {
return assertThat((Object) actual);
}
public void isTheSameXmlAs(Document expected) {
isTheSameXmlAs((Object) expected);
}
public static XmlSubject assertThat(Document actual) {
return assertThat((Object) actual);
}
public void isTheSameXmlAs(String expected) {
isTheSameXmlAs((Object) expected);
}
public static XmlSubject assertThat(String actual) {
return assertThat((Object) actual);
}
public void isTheSameXmlAs(URL expected) {
isTheSameXmlAs((Object) expected);
}
public static XmlSubject assertThat(URL actual) {
return assertThat((Object) actual);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment