【发布时间】: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