@Autowire MockMvc - Spring Data Rest

允我心安 提交于 2021-02-07 18:41:36

问题


Given the Repository

public interface ResourceRepository extends CrudRepository<Resource, Long> { ... }

The following test code:

@WebMvcTest
@RunWith(SpringRunner.class)
public class RestResourceTests {

  @Autowired
  private MockMvc mockMvc;

  @Test
  public void create_ValidResource_Should201() {
    String requestJson = "...";

    mockMvc.perform(
      post("/resource")
        .content(requestJson)
        .contentType(MediaType.APPLICATION_JSON))
      .andExpect(status().isCreated()); // This fails with 404
  }

}

In order to fix the issue, I need to inject the WebApplicationContext and manually create the MockMvc object as follows:

@SpringBootTest
@RunWith(SpringRunner.class)
public class RestResourceTests {

  private MockMvc mockMvc;

  @Autowired
  private WebApplicationContext webApplicationContext;

  @Before
  public void setup() {
    this.mockMvc = webAppContextSetup(webApplicationContext).build();
  }

Is there a simpler way to achieve this?

Thanks!


回答1:


I figured out a "clean" solution, but it feels like a bug to me.

@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc // <-- this is the fix 
public class RestResourceTests {

  @Autowired
  private MockMvc mockMvc; // <-- now injects with repositories wired.

The reason I feel like this is a bug, the @WebMvcTest annotation already places the @AutoConfigureMockMvc annotation on the class under test.

It feels like @WebMvcTest isn't looking at the web components loaded with @RestRepository.



来源:https://stackoverflow.com/questions/48589893/autowire-mockmvc-spring-data-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!