需要先进行导包
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-params -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
常用注解
断言
假设
package org.example;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class UtilsTest {
/*@BeforeAll 在所有测试方法之前执行,只执行一次*/
@BeforeAll
static void beforeAll(){
System.out.println("BeforeAll");
}
/*@BeforeEach 每次执行测试方法之前会执行一遍*/
@BeforeEach
void beforeEach(){
System.out.println("BeforeEach");
}
@Test
void test1() {
System.out.println("test1");
}
/*@Order是定义执行顺序,需要配合@TestMethodOrder(MethodOrderer.OrderAnnotation.class)注解使用
* @DisplayName 定义显示测试类的方法
* */
@Test
@DisplayName("---test2---")
@Order(1)
void test2() {
System.out.println("test2");
}
/*@Disabled 测试方法不执行*/
@Test
@Disabled
void test3() {
System.out.println("test3");
}
/* @Tag 为测试类添加标签
* @RepeatedTest 定义额外执行的次数
* */
@Test
@Tag("---test4---")
@RepeatedTest(1)
void test4() {
System.out.println("test4");
}
/*@AfterAll 在所有测试方法之后执行,只执行一次*/
@AfterAll
static void afterAll(){
System.out.println("AfterAll");
}
/*@AfterEach 每次执行测试方法之后的时候执行一遍*/
@AfterEach
void afterEach(){
System.out.println("AfterEach");
}
}
/**
* DisplayName中带有emoji,在测试框架中能够展示
*/
@Test
@DisplayName("测试service层的increase方法\uD83D\uDE31")
void increase() {
System.out.println("execute increase");
assertEquals(helloService.increase(1),2);
assertTrue(1==1);
assertAll(
() -> assertEquals(helloService.increase(1),2),
() -> assertEquals(helloService.hello(NAME),"Hello " + NAME)
);
异常
在某些情况下,期望方法在特定条件下引发异常。 如果给定方法未引发指定的异常,则assertThrows将使测试失败。
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("Illegal Argument Exception occured");
});
assertEquals("Illegal Argument Exception occured", exception.getMessage());
@TimeOut注解:程序运行超过指定的时间的话,就会自动报错。
第一个参数是数值,第二个参数是单位。(有天、小时、分钟、秒、毫秒等等)
Timeout(value = 500,unit = TimeUnit.MILLISECONDS)
@Test
public void testTimeout() throws InterruptedException {
Thread.sleep(600);
}
@Order是定义执行顺序,
需要配合@TestMethodOrder(MethodOrderer.OrderAnnotation.class)注解使用
@SpringBootTest
在SpringBoot中,进行测试要在类的前面添加@SpringBootTest方法
@SpringBootTest