spring-boot web测试层学习记录

来源:互联网 发布:最全的淘宝隐藏券网站 编辑:程序博客网 时间:2024/06/06 12:25

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

@Autowiredprivate A a;

method

@TestassertThat(controller).isNotNull();

模拟http请求测试

class

@RunWith(SpringRunner.class)<!-- 自定义端口 -->@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)

params

@LocalServerPortprivate int port;@Autowiredprivate 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

@Autowiredprivate MockMvc mockMvc;@MockBeanprivate 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")));