首先,使用Spring上下文测试控制器不是单元测试。您应该考虑通过对依赖项使用mock并创建
standalone mock MVC
:
public class MyControllerTest {
@InjectMocks
private MyController tested;
// add @Mock annotated members for all dependencies used by the controller here
private MockMvc mvc;
// add your tests here using mvc.perform()
@Test
public void getHealthReturnsStatusAsJson() throws Exception {
mvc.perform(get("/health"))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.status", is("OK")));
}
@Before
public void createControllerWithMocks() {
MockitoAnnotations.initMocks(this);
MockMvcBuilders.standaloneSetup(controller).build()
}
}
如果使用外部
@ControllerAdvice
通过简单调用
setControllerAdvice()
在MVC生成器上。
这样的测试在并行运行时没有问题,而且速度更快,根本不需要设置Spring上下文。
您描述的部分集成测试对于确保使用正确的接线以及所有测试单元按预期协同工作也很有用。但我更倾向于进行更通用的集成测试,包括多个/所有端点检查它们是否正常工作(不检查边缘情况),以及仅模拟外部服务(如内部REST客户端,将数据库替换为内存中的数据库,…)。使用此设置,您可以从一个新的数据库开始,甚至可能不需要回滚任何事务。当然,使用数据库迁移框架(如
Liquibase
这将动态设置内存中的db。