关键字: MockMvc,@AutoConfigureMockMvc,@SpringBootTest,@RunWith,@MockBean
1.简介
根本不启动服务器,而是只测试下面的层,在那里Spring处理传入的HTTP请求并将其传递给控制器。这样,几乎使用了整个堆栈,并且调用代码的方式与处理真正的HTTP请求的方式完全相同,但不需要启动服务器。
等价意义
@AutoConfigureMockMvc注解,自动注入MockMvc,自动注入Service。
使用MockMvc发起请求,然后执行相应的代码,在执行的过程中使用Mockito的mock模拟底层数据的返回,最后结果验证。
常用于对Controller进行单元测试。
2.详细说明
2.1.pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.1.5.RELEASE</version>
<scope>test</scope>
</dependency>
2.2.样例
@RunWith(SpringRunner.class)
@SpringBootTest(classes = JpaApplication.class)
@AutoConfigureMockMvc
public class StudentMasterControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void getStudentMaster() throws Exception {
mvc.perform(get("/studentMaster/getStudentMaster")
.accept(MediaType.APPLICATION_JSON)
.param("studentId", "201903_000006")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andDo(print())
.andReturn();
}
}
3.相关知识
@SpringBootTest是SpringBoot的一个用于测试的注解,通过SpringApplication在测试中创建ApplicationContext。
@RunWith(SpringRunner.class),就是指用SpringRunner来运行,SpringRunner是SpringJunit4ClassRunner的别名。
@MockBean是模拟相应对象,使用mock对象代替原来spring的bean,然后模拟底层数据的返回,而不是调用原本真正的实现。
SpringBoot 中, @MockBean 会将mock的bean替换掉 SpringBoot 管理的原生bean,从而达到mock的效果。
mock:在软件开发的世界之外, "mock"一词是指模仿或者效仿. 因此可以将“mock”理解为一个替身,替代者. 在软件开发中提及"mock",通常理解为模拟对象或者Fake