Spring-hateoas: Integrate Traverson to MockMvc tests

Created on 16 Aug 2018  路  3Comments  路  Source: spring-projects/spring-hateoas

I typically write tests with MockMvc where you can set up expectations using very nice DSL.
Test is annotated with

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc

Then I can autowire

@Autowired
MockMvc mvc

Then I can do mvc.perform(get("URI where I want to go"))
.andExpect(status().isOk()) and other expectations

"URI where I want to go" is concatenated list of resources and I thought I could start using Traverson to do navigation for me.

I thought I would be able to use it, but as of now I need fully-blown server.
Could you please extend Traverson to allow using it in MockMvc tests?

Most helpful comment

Hi, it is already possible:

Traverson traverson = new Traverson(new URI(RestApi.ROOT), MediaTypes.HAL_JSON);
MockMvcClientHttpRequestFactory requestFactory = new MockMvcClientHttpRequestFactory(mockMvc);
traverson.setRestOperations(new RestTemplate(requestFactory));

YourResource resource = traverson
        .follow("first-step")
        .follow(rel("second-step").withParameter("param", "param-value"))
        .toObject(YourResource.class);

assertThat(resource, notNullValue());

All 3 comments

Hi, it is already possible:

Traverson traverson = new Traverson(new URI(RestApi.ROOT), MediaTypes.HAL_JSON);
MockMvcClientHttpRequestFactory requestFactory = new MockMvcClientHttpRequestFactory(mockMvc);
traverson.setRestOperations(new RestTemplate(requestFactory));

YourResource resource = traverson
        .follow("first-step")
        .follow(rel("second-step").withParameter("param", "param-value"))
        .toObject(YourResource.class);

assertThat(resource, notNullValue());

Any chance you could post a more complete example? Specifically how to assert on the traversed link?

Was this page helpful?
0 / 5 - 0 ratings