在 java 单元测试中,使用 assertions 断言主要依赖 junit jupiter 提供的 org.junit.jupiter.api.assertions 类。通过调用其静态方法如 assertequals、asserttrue 和 assertthrows,可以验证代码执行结果是否符合预期,并在测试失败时提供清晰的错误信息。

如何验证基本类型与对象的相等性
对于基本数据类型和字符串,直接使用 assertEquals 即可;对于对象引用或复杂结构,需关注 equals() 方法的实现或使用 assertThat(Hamcrest)进行更灵活的匹配。

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class BasicAssertionTest {
@Test
public void testEquality() {
int expected = 42;
int actual = calculateValue();
assertEquals(expected, actual, "计算值应等于42");
String str1 = "hello";
String str2 = new String("hello");
assertEquals(str1, str2, "字符串内容应相同");
}
private int calculateValue() {
return 6 * 7;
}
}
如何处理异常与集合断言
当需要验证代码是否抛出特定异常时,使用 assertThrows 方法;对于集合或数组,可以使用 assertIterableEquals 来确保顺序和内容完全一致,避免仅检查大小导致的误判。

import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class AdvancedAssertionTest {
@Test
public void testExceptionAndCollection() {
// 验证异常
Exception exception = assertThrows(IllegalArgumentException.class, () -> {
throwMethod();
});
assertEquals("Invalid input", exception.getMessage());
// 验证集合
List<string> expectedList = List.of("a", "b");
List<string> actualList = getItems();
assertIterableEquals(expectedList, actualList, "列表内容应一致");
}
private void throwMethod() {
throw new IllegalArgumentException("Invalid input");
}
private List<string> getItems() {
return List.of("a", "b");
}
}</string></string></string>
当输入为 null 时断言行为如何
当传入的期望值或实际值为 null 时,assertEquals 会调用对象的 equals 方法进行比较,若两者均为 null 则视为相等;若一方为 null 另一方非空,则断言失败。建议使用 assertNull 或 assertNotNull 明确表达意图。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











