跳到主要内容

JUnit

JUnit4

Junit4 中使用注释类识别:@Test
@Before
@After
异常测试

断言

org.junit.Assert

Matches

TestCase TestSuite TestFixture TestResult TestRunner TestListener Assert

测试方法没有返回值,没有参数,用 @Test 表示测试方法

单独测试某个测试方法,选中方法,右键,JUnit Test 即可测试单个方法

在 JUnit 中执行事务方法,默认在方法执行完成后,执行回滚操作

@Test
@Transactional
@Commit
public void test() {
// ...
}

JUnit 使用

1、指定方法的执行顺序

  • 通过 @TestMethodOrder(MethodOrderer.OrderAnnotation.class) 指定测试方法的执行顺序。
  • 通过 @Order(1) 指定执行方法顺序,数字越小,优先级越高。
import lombok.extern.slf4j.Slf4j;  
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;

import java.io.IOException;

/**
* @author wangzhy * @since 2023年10月19日
*/
@Slf4j
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class MethodOrdererTest {
@Test
@Order(1)
void testA() throws IOException {
log.info("testA order:1");
}
@Test
@Order(3)
void testB() throws IOException {
log.info("testB order:3");
}
@Test
@Order(2)
void testC() throws IOException {
log.info("testC order:2");
}
@Test
@Order(5)
void testD() throws IOException {
log.info("testD order:5");
}
@Test
@Order(4)
void testF() throws IOException {
log.info("testF order:4");
}
}

执行结果

2023-10-19 17:39:54.521 [main] INFO  c.w.t.MethodOrderTest : testA order:1
2023-10-19 17:39:54.600 [main] INFO c.w.t.MethodOrderTest : testC order:2
2023-10-19 17:39:54.605 [main] INFO c.w.t.MethodOrderTest : testB order:3
2023-10-19 17:39:54.610 [main] INFO c.w.t.MethodOrderTest : testF order:4
2023-10-19 17:39:54.614 [main] INFO c.w.t.MethodOrderTest : testD order:5