As using elements directly to compare will cause issues in case you have prefixes and don't wish to import the whole xml, you can compare sections of xml (Element) this way.
- W3C DOM (Included in Java 16) For testing
- XMLUnit Core
- XMLUnit Matchers
- Hamcrest
- JUnit
[...]
dependencies {
implementation 'org.glassfish.jaxb:jaxb-runtime:3.0.2'
testImplementation 'org.xmlunit:xmlunit-core:2.9.0'
testImplementation 'org.xmlunit:xmlunit-matchers:2.9.0'
testImplementation 'org.hamcrest:hamcrest:2.2'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}
[...]
Create a @beforeAll
which is going to create the document builder in a test class.
class DOMTest {
private static DocumentBuilder documentBuilder;
@BeforeAll
static void setup() throws ParserConfigurationException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilder = documentBuilderFactory.newDocumentBuilder();
}
[...]
}
@Test
void compare2externalFiles() throws IOException, SAXException {
Document fileA = documentBuilder.parse(
getClass().getClassLoader().getResourceAsStream("fileA.xml"));
Document fileB = documentBuilder.parse(
getClass().getClassLoader().getResourceAsStream("fileB.xml"));
assertThat(
expected, CompareMatcher.isIdenticalTo(doc2).ignoreWhitespace()
);
}
WARNING: The document must be the same used to create your element.
@Test
void compareExternalWithInternal() throws IOException, SAXException {
Document fileA = documentBuilder.parse(
getClass().getClassLoader().getResourceAsStream("fileA.xml"));
Document document = documentBuilder.newDocument(); // must be the same document used to create the element.
document.appendChild(null); //replace null with the XML element you want there
assertThat(
fileA, CompareMatcher.isIdenticalTo(document).ignoreWhitespace()
);
}
WARNING: The document must be the same used to create your element.
@Test
void compare2Internals() {
Document documentA = documentBuilder.newDocument(); // must be the same document used to create the element.
documentA.appendChild(elementA); //replace with the XML element you want there
Document documentB = documentBuilder.newDocument();
documentB.appendChild(elementB);
assertThat(
documentA, CompareMatcher.isIdenticalTo(documentB).ignoreWhitespace()
);
}