spring boot web层测试
Author : Janloong Do_O
依赖注入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
测试层
controller基础测试
单次测试,实例化context一次 ,多次测试间不共用context,每次生成一个
若需要多次测试间共用一个context , 需要在类级上使用注解 @DirtiesContext
该部分context理解还不够,可能不正确
class
@RunWith(SpringRunner.class)
@SpringBootTest
params
@Autowired
private A a;
method
@Test
assertThat(controller).isNotNull();
模拟http请求测试
class
@RunWith(SpringRunner.class)
<!-- 自定义端口 -->
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
params
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
method
@Test
assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/",
String.class)).contains("Hello World");
仿真多http应用级请求测试
class
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
这里针对实际web层请求可以使用注解
@RunWith(SpringRunner.class)
@WebMvcTest
单个注入时
@WebMvcTest(a-controller.class)
params
@Autowired
private MockMvc mockMvc;
method
this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
依赖性controller层注入
class
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
params
@Autowired
private MockMvc mockMvc;
@MockBean
private GreetingService greetingService;
method
when(greetingService.greet()).thenReturn("Hello Mock");
this.mockMvc.perform(get("/greeting")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello Mock")));