spring-projects / spring-hateoas

Spring HATEOAS - Library to support implementing representations for hyper-text driven REST web services.
https://spring.io/projects/spring-hateoas
Apache License 2.0
1.03k stars 475 forks source link

Integrate Traverson to MockMvc tests #733

Open pmihalcin opened 6 years ago

pmihalcin commented 6 years ago

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?

peter-san commented 6 years ago

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());
rodmccutcheon commented 5 years ago

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

reda-alaoui commented 4 years ago

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

reda-alaoui commented 1 year ago

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.