SpringBoot单元测试

2019-10-06  本文已影响0人  GambitP_P

1、Spring Boot的单元测试

  1. 依赖Maven配置
<!--springboot程序测试依赖,如果是自动创建项目默认添加-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
  1. 示例代码
@RunWith(SpringRunner.class) //底层用junit
@SpringBootTest(classes = {SpringbootDemoApplication.class}) //启动整个springboot项目
public class SpringbootDemoApplicationTests {

    @Test
    public void testOne() {
        System.out.println("test hello 1");
        TestCase.assertEquals(1, 1);
    }

    @Before
    public void testBefore() {
        System.out.println("before");
    }

    @After
    public void testAfter() {
        System.out.println("after");
    }

}

2、MockMvc模拟Http请求测试

  1. 使用说明
    测试类增加类注解 @AutoConfigureMockMvc
  2. MockMvc相关API
    perform:执行一个RequestBuilder请求
    andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则
    andReturn:最后返回相应的MvcResult->Response
  3. 示例代码
@RunWith(SpringRunner.class) //底层用junit
@SpringBootTest(classes = {SpringbootDemoApplication.class}) //启动整个springboot项目
@AutoConfigureMockMvc
public class SpringbootDemoApplicationTests {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void apiTest() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/testjson"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn();
        System.out.println(mvcResult.getResponse().getStatus()); //获取http状态码
        System.out.println(mvcResult.getResponse().getContentAsString()); //获取响应数据
    }

}
上一篇 下一篇

猜你喜欢

热点阅读