spring-boot web测试层学习记录

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")));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值