@Autowire MockMvc - Spring Data Rest [英] @Autowire MockMvc - Spring Data Rest
问题描述
给定存储库
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
对象,如下所示:
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?
谢谢!
推荐答案
我想出了一个干净"的解决方案,但对我来说就像一个错误.
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.
我觉得这是一个错误的原因,@WebMvcTest
注释已经在被测类上放置了 @AutoConfigureMockMvc
注释.
The reason I feel like this is a bug, the @WebMvcTest
annotation already places the @AutoConfigureMockMvc
annotation on the class under test.
感觉 @WebMvcTest
并没有查看加载了 @RestRepository
的 Web 组件.
It feels like @WebMvcTest
isn't looking at the web components loaded with @RestRepository
.
这篇关于@Autowire MockMvc - Spring Data Rest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!