Search code examples
unit-testinghamcrest

hamcrest - how to negate hasXPath to test document does not contain certain child node?


I want to test that some XML document does not contain certain XPath, how should I assert that in unit test using Hamcrest matcher?

For example I want to assert the document has no foo/bar under pos:

    assertThat(document, Matchers.hasXPath(
            "/svc_result/slia/pos/foo/bar)]")  # negate here
    );

Solution

  • We should use XPath negate, as Hamcrest does not support matcher negation:

        assertThat(document, Matchers.hasXPath(
                "/svc_result/slia/pos[not(foo/bar)]")
        );
    

    parent[not(xxx)] means "this XPath parent does not contain a child node xxx".