spring-hateoas icon indicating copy to clipboard operation
spring-hateoas copied to clipboard

Integrate Traverson to MockMvc tests

Open pmihalcin opened this issue 7 years ago • 4 comments
trafficstars

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?

pmihalcin avatar Aug 16 '18 11:08 pmihalcin

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());

peter-san avatar Sep 13 '18 06:09 peter-san

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

rodmccutcheon avatar Mar 28 '19 05:03 rodmccutcheon

My workaround is https://gist.github.com/reda-alaoui/9af8e9c10ed7f9e72a42245af512e0e3

reda-alaoui avatar Apr 12 '20 20:04 reda-alaoui

My workaround is https://gist.github.com/reda-alaoui/9af8e9c10ed7f9e72a42245af512e0e3

The initial workaround has gained more HAL/HAL-FORMS features.

I turned it into https://github.com/Cosium/hal-mock-mvc for anyone interested. It is a full blown library allowing to easily test Spring HATEOAS HAL(-FORMS) endpoints.

reda-alaoui avatar May 21 '23 18:05 reda-alaoui