【问题标题】:@Autowire MockMvc - Spring Data Rest@Autowire MockMvc - 弹簧数据休息
【发布时间】:2018-07-13 09:07:42
【问题描述】:

给定存储库

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

以下测试代码:

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

}

为了解决这个问题,我需要注入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();
  }

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

谢谢!

【问题讨论】:

  • 第一个 impl 会发生什么错误?
  • 我一直都是这样做的。通常我有一个抽象类来设置 MockMvc 实例,因为我还应用了一些安全过滤器和 restdoc 配置。
  • @DarrenForsythe it 404's I put a comment in the expect.
  • 你可以为 spring web 设置调试日志和/或发布控制器吗?两者之间应该没有真正的区别。
  • 本身没有控制器,我添加了一个示例 Spring Data Repository

标签: spring-boot spring-data-rest spring-test-mvc


【解决方案1】:

我想出了一个“干净”的解决方案,但对我来说这就像一个错误。

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

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

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

感觉就像@WebMvcTest 没有查看加载有@RestRepository 的Web 组件。

【讨论】:

  • 文档对此非常具体。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-28
  • 2017-10-01
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
  • 2018-12-27
相关资源
最近更新 更多