@Autowire MockMvc-弹簧数据剩余

dar*_*rdo 3 spring-data-rest spring-test-mvc spring-boot

给定存储库

public interface ResourceRepository extends CrudRepository<Resource, Long> { ... }
Run Code Online (Sandbox Code Playgroud)

以下测试代码:

@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
  }

}
Run Code Online (Sandbox Code Playgroud)

为了解决此问题,我需要注入WebApplicationContext和手动创建MockMvc对象,如下所示:

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

  private MockMvc mockMvc;

  @Autowired
  private WebApplicationContext webApplicationContext;

  @Before
  public void setup() {
    this.mockMvc = webAppContextSetup(webApplicationContext).build();
  }
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法来实现这一目标?

谢谢!

dar*_*rdo 6

我想出了一个“干净”的解决方案,但对我来说却像个虫子。

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

  @Autowired
  private MockMvc mockMvc; // <-- now injects with repositories wired.
Run Code Online (Sandbox Code Playgroud)

我觉得这是一个错误的原因,@WebMvcTest注解已经将@AutoConfigureMockMvc注解放置在要测试的类上。

感觉好像@WebMvcTest没有在查看加载了的Web组件@RestRepository