Springboot2.x单元测试

时间:2021-10-03 22:02:21

简介:讲解SpringBoot的单元测试
1、引入相关依赖
<!--springboot程序测试依赖,如果是自动创建项目默认添加-->

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

 

2、使用
@RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner
@SpringBootTest(classes={DemoApplication.class})// 指定启动类,启动整个springboot工程

package net.nbclass.demo;

import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {DemoApplication.class})
public class DemoApplicationTests {

    @Test
    public void contextLoads() {
        System.out.println("测试中1");
        // 断言
        TestCase.assertEquals(1,1);
    }

    @Test
    public void contextLoads1() {
        System.out.println("测试中2");
        TestCase.assertEquals(1,1);
    }

    @Before
    public void testBefore(){
        System.out.println("测试前");
    }

    @After
    public void testAfter(){
        System.out.println("测试后");
    }

}

单独测试只需要运行对应的@test注解的方法就可以,全部测试就运行DemoApplicationTests 类就可以了

 

以下是测试API的,增加类注解 @AutoConfigureMockMvc

 

package net.nbclass.demo;

import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {DemoApplication.class})
@AutoConfigureMockMvc  //测试接口用
public class DemoApplicationTests {
  
    @Before
    public void testBefore(){
        System.out.println("测试前");
    }

    @After
    public void testAfter(){
        System.out.println("测试后");
    }

    //下面是测试接口
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void apiTest()throws Exception{
        MvcResult mvcResult=mockMvc.perform(MockMvcRequestBuilders.get("/get")).
                andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
        int status=mvcResult.getResponse().getStatus();                              ----打印出状态码,200就是成功
        System.out.println(status);
    }

}