SpringBoot单元测试
SpringBoot整合juint5
-
介绍
-
Junit5三个框架如图,jupiter是junit的核心,需要运行在platform上,vintag3则是兼容旧版引擎
-
导入依赖
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
- 注意:这里scope如果是test,则只能在test文件夹下使用junit
-
基本使用:
-
//需要使用SpringBootTest注解标识,参数为SpringBootApplication所在类 @SpringBootTest(classes = App.class) public class TestJdbc { //注意导包为 org.junit.jupiter.api.Test; @Test public void t1(){ System.out.println("test"); } }
Junit常用注解
- 注意:运行maven中test可以生成测试日志
@DisplayName("junit单元测试")
@SpringBootTest(classes = {App.class})
public class TestJunit {
@BeforeEach //在每个单元测试方法之前执行
public void beforeEach(){
System.out.println("这是beforeEach方法.....");
}
@AfterEach//在每个单元测试方法之后执行
public void afterEach(){
System.out.println("这是afterEach方法.....");
}
@BeforeAll//在所有测试方法之前执行,注意方法必须是static修饰的
public static void beforeAll(){
System.out.println("这是beforeAll方法......");
}
@AfterAll //在所有测试方法之后执行
public static void afterAll(){
System.out.println("这是afterAll方法");
}
@Test
public void test01(){
System.out.println("这是test01方法");
}
@Test
@Disabled //执行某一个测试方法不执行
public void test02(){
System.out.println("这是test02方法");
}
@DisplayName("测试方法是否超时")
@Test
@Timeout(value = 500,unit = TimeUnit.MILLISECONDS)//执行方法在500毫秒之内执行完成,如果超过了指定的运行时间,就执行报错
public void test03(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("这是test03方法");
}
}
结果:
Assert断言使用
Java代码:
@SpringBootTest(classes = {App.class})
public class TestAssertion {
@Test
public void test(){
int[] arr1=new int[]{1,2,3};
Assertions.assertAll("header",()->
Assertions.assertSame(new Object(),new Object(),"断言失败信息1"),
()->Assertions.assertArrayEquals(new int[]{1,2,3},new int[]{1,2},"断言失败信息2"));
Assertions.assertTrue(1!=2,"msg");
}
}
断言失败则抛出异常:
前置条件Assume
与断言类似,但是在assume为假时方法相当于没有执行,与disabled结果相同,被跳过
@Test
public void test(){
Assumpotions.assumeTrue(1==2,"maassage")
}
结果:
参数化测试
参数化测试时junit5的新特性,可以一次性批量测试
注解模板
@ParameterizedTest
//不需要@test
@MethodSource("MethodsOfStream")
或者
@ValueSource(strings = {"apple", "orange", "banana"})
Java代码
@ParameterizedTest
@ValueSource(strings = {"app"})
public void t(String app){
System.out.println(app);
}
结果: