Logo
Section 1 / 9

使用 JUnit 6 进行单元测试

学习通过编写、组织和执行健壮的单元测试,使用 JUnit 6 框架实现代码验证的自动化。

导入

使用 JUnit 6 进行单元测试

学习通过编写、组织和执行健壮的单元测试,使用 JUnit 6 框架实现代码验证的自动化。

...
按速度和隔离性对测试进行分类
1// 我们的被测系统(SUT) 2class Calculator { 3 public int add(int a, int b) { 4 return a + b; 5 } 6 7 public int divide(int a, int b) { 8 if (b == 0) throw new IllegalArgumentException("Cannot divide by zero"); 9 return a / b; 10 } 11}
1import org.junit.jupiter.api.Test; 2import org.junit.jupiter.api.Assertions; 3 4public class MainTest { 5 6 @Test 7 void testAddition() { 8 Calculator calculator = new Calculator(); 9 int result = calculator.add(2, 3); 10 11 // 此断言自动验证正确性 12 // 如果 2 + 3 不等于 5,则测试失败 13 Assertions.assertEquals(5, result, "2 + 3 应等于 5"); 14 } 15}
1import org.junit.jupiter.api.Test; 2import org.junit.jupiter.api.Assertions; 3 4public class MainTest { 5 6 @Test 7 void testConditionals() { 8 boolean isServerUp = true; 9 String databaseName = "Employees"; 10 11 // 验证某个条件为真 12 Assertions.assertTrue(isServerUp, "服务器应处于运行状态"); 13 14 // 验证某个条件为假 15 Assertions.assertFalse(5 > 10, "5 不大于 10"); 16 17 // 验证对象不为 null 18 Assertions.assertNotNull(databaseName, "数据库名称应存在"); 19 } 20}
1import org.junit.jupiter.api.Test; 2import org.junit.jupiter.api.Assertions; 3 4public class MainTest { 5 6 @Test 7 void testDivisionByZero() { 8 Calculator calculator = new Calculator(); 9 10 // 此测试仅在 lambda 抛出 IllegalArgumentException 时通过 11 IllegalArgumentException exception = Assertions.assertThrows( 12 IllegalArgumentException.class, 13 () -> calculator.divide(10, 0) 14 ); 15 16 // 我们也可以检查异常消息 17 Assertions.assertEquals("Cannot divide by zero", exception.getMessage()); 18 } 19}
1import org.junit.jupiter.api.Test; 2import org.junit.jupiter.api.BeforeEach; 3import org.junit.jupiter.api.AfterEach; 4import org.junit.jupiter.api.Assertions; 5import java.util.ArrayList; 6import java.util.List; 7 8public class MainTest { 9 10 private List<String> inventory; 11 12 @BeforeEach 13 void setUp() { 14 // 在每个测试前运行,以确保从干净的初始状态开始 15 inventory = new ArrayList<>(); 16 inventory.add("Apple"); 17 inventory.add("Banana"); 18 } 19 20 @Test 21 void testAdd() { 22 inventory.add("Orange"); 23 // 我们知道 'inventory' 最初有 2 个元素,因为 @BeforeEach 已执行 24 Assertions.assertEquals(3, inventory.size()); 25 } 26 27 @Test 28 void testRemove() { 29 inventory.remove("Apple"); 30 // 此测试不受 testAdd 影响,因为 @BeforeEach 重置了列表 31 Assertions.assertEquals(1, inventory.size()); 32 } 33 34 @AfterEach 35 void tearDown() { 36 // 在每个测试后运行。如果需要,可用于关闭资源。 37 inventory.clear(); 38 } 39}
1import org.junit.jupiter.api.Test; 2import org.junit.jupiter.api.DisplayName; 3import org.junit.jupiter.api.Disabled; 4import org.junit.jupiter.api.Assertions; 5 6@DisplayName("用户账户系统测试") 7public class MainTest { 8 9 @Test 10 @DisplayName("当邮箱有效时应创建用户") 11 void testUserCreation() { 12 Assertions.assertTrue(true); 13 } 14 15 @Test 16 @Disabled("功能待实现") 17 void testUserDeletion() { 18 // 此测试将被测试运行器跳过 19 } 20}

反射与元数据

Java 中的日志记录