spring-projects / spring-data-rest

Simplifies building hypermedia-driven REST web services on top of Spring Data repositories
https://spring.io/projects/spring-data-rest
Apache License 2.0
919 stars 563 forks source link

Autowiring MockMvc with @WebMvcTest [DATAREST-1194] #1559

Open spring-projects-issues opened 6 years ago

spring-projects-issues commented 6 years ago

Jonathan Kupcho opened DATAREST-1194 and commented

I noticed when using @WebMvcTest, an @Autowired MockMvc doesn't include the Data REST paths. For example:

@WebMvcTest
@RunWith(SpringRunner.class)
public class ResourceTest {
  @Autowired
  private MockMvc mockMvc; // this injects, but you can't call Data REST endpoints

You can get around this by doing the normal @SpringBootTest and @RunWith(SpringRunner.class) then adding the @AutoConfigureMockMvc, like so:

@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
public class ResourceTest {
  @Autowired
  private MockMvc mockMvc; // this injects, and you can call Data REST endpoints

This seemed strange to me due to @WebMvcTest including @AutoConfiguerMockMvc. I'm not sure if this is by design, or a context loading issue. I've included my associated StackOverflow post, and some sample code in the comments.

Thanks!


Affects: 2.6.10 (Ingalls SR10)

Reference URL: https://stackoverflow.com/questions/48589893/autowire-mockmvc-spring-data-rest/48626397

1 votes, 2 watchers

spring-projects-issues commented 6 years ago

Jonathan Kupcho commented

Below is a sample repo which demonstrates the problem.

https://github.com/jkupcho/mock-mvc-issue

spring-projects-issues commented 4 years ago

bschoenmaeckers commented

This solution is very flaky. On my setup it works half of the time

spring-projects-issues commented 4 years ago

Jonathan Kupcho commented

I opened this issue 2 years ago, implementation behind this has probably change quite a bit since then, plus it wasn’t a catch all just an example of how one might be able to accomplish.

At this point there’s probably a better way and it’d probably be best to dig through the docs a bit more