Skip to content

Add new html content matcher for MockMvcResultMatchers [SPR-16097] #20646

@spring-projects-issues

Description

@spring-projects-issues

Leonard Brünings opened SPR-16097 and commented

The current ContentResultMatchers have direct support for plain strings, json, and xml. I would propose to add another that supports the usage of cssQuery and DOM operations.

Using https://jsoup.org/ I've created a small POC and it was rather easy to get this example implemented.

This example checks if the csrf token was correctly injected by spring security.

mockMvc.perform(get("/").with(user("user")))
		.andExpect(status().is2xxSuccessful())
		.andExpect(html(contains("form input[type=hidden][name=_csrf]")));

I don't think that there is a way to do the same with the current available methods, the closest would be a containsString("<input type=\"hidden\" name=\"_csrf\"") matcher on the body content, and this only works if the value attribute comes after the name attribute. And it still doesn't check if it is part of the form.

The challenge that I see is to have an expressive syntax without performing redundant work, e.g., only parse the body content into a Document once.
Furthermore, we'd need expressions for singular and multiple results, since cssQuery can match more than one Element.

This is just an example what could be done, suggestions welcome.

andExpect(
    content().html()
        .toMatch(anElement("form input[type=hidden][name=_csrf]").withAttribute("value", matchesPattern(UUID_PATTERN)))
        .toMatch(elements("form input").count(5))
)

0 votes, 5 watchers

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: testIssues in the test modulestatus: declinedA suggestion or change that we don't feel we should currently applytype: enhancementA general enhancement

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions