Test XML content without using mock mvc

1.1k views Asked by At

I am using spring test with mockmvc and it works like a charm to test xml output!

Example:

ResultActions actions = this.mockMvc.perform(get("/entry/NX_P38398/overview.xml"));
actions.andExpect(xpath("entry/overview/gene-name-list/gene-name[@type='recommended']").exists());
actions.andExpect(xpath("entry/overview/gene-name-list/gene-name[@type='recommended']").string("BRCA1"));

I would like to take advantage of the same features to test an OutputStream without using mockmvc and controllers. Is it possible to use the same ResultMatcher?

Example (pseudo code):

XMLContent xmlContent = new XMLContent("<entry>...</entry>");
AssertTrue(xmlContent.andExpect(xpath("entry/overview/gene-name-list/gene-name[@type='recommended']").exists());

I know it exists XMLUnit http://xmlunit.sourceforge.net/userguide/html/ar01s05.html or other libraries, but I would like to re-use the same ResultMatcher.

Thanks

1

There are 1 answers

0
Sam Brannen On BEST ANSWER

No, it's not possible to reuse XpathResultMatchers without MockMvc and related classes.

However... the code in question (in your pseudo-code example), delegates internally to Spring's XpathExpectationsHelper. So you can invoke -- for example -- the exists() method directly on an instance of XpathExpectationsHelper if you so desire.

As an alternative, you could write your own simple assertions based on XPath using javax.xml.xpath.XPath which is what XpathExpectationsHelper uses internally anyway. Or... as you mentioned, just use the built-in support for XPath in XMLUnit.