SpringBoot单元测试之配置流程
环境:
SpringBoot 2.3
1、依赖
<!--springboot程序测试依赖,如果是⾃动创建项⽬默认添加-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
2、注解
在需要的测试类的类名前添加以下注解:
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) //底层⽤junit SpringJUnit4ClassRunner
@SpringBootTest(classes={SSMdemoApplication.class})//启动整个springboot⼯程的入口类
public class SpringBootTestModel{
3、流程
一般情况下需要用到三个注解:
@Before
@Test
@After
使用的方式如下:
@Before
public void testBefore(){
System.out.println("这是测试@Before,加载数据一般放到这里");
}
@Test
public void testModel_1(){
System.out.println("这是测试方法---1---");
}
@Test
public void testModel_2(){
System.out.println("这是测试方法---2---");
}
@After
public void testAfter(){
System.out.println("这是测试@After,释放资源一般放到这里");
}
4、注意:
(1)执行一个单独的方法
(2)同时执行两个测试方法
每一个测试方法都会有单独的@Before和@After与之匹配,执行结果如下:
5、拓展
一般经常用TestCase.assert…来测试希望得到的结果,和测试返回的结果是否一致
@Test
public void testModel_2(){
System.out.println("这是测试方法---2---");
TestCase.assertEquals(12,25);
}
结果: