理论知识
1. 什么是单元测试?
单元测试是对软件中最小的功能单元(如方法或类)进行验证的测试,确保其行为符合预期。
作用:
- 提高代码质量,避免潜在的缺陷。
- 支持重构和快速验证功能。
- 提高开发效率。
2. JUnit 的核心注解:
@Test
:标记为测试方法。@Before
:在每个测试方法之前执行,用于初始化。@After
:在每个测试方法之后执行,用于清理资源。@BeforeClass
和@AfterClass
:在所有测试方法之前和之后执行,适合静态资源初始化和清理。
3. 常用断言:
assertEquals(expected, actual)
:断言两个值相等。assertTrue(condition)
:断言条件为true
。assertThrows(Exception.class, () -> method())
:断言方法抛出指定异常。
实践操作:为字符串工具类编写单元测试
工具类代码:StringUtil.java
public class StringUtil {
public static String reverse(String input) {
if (input == null) {
throw new IllegalArgumentException("Input cannot be null");
}
return new StringBuilder(input).reverse().toString();
}
public static String concatenate(String str1, String str2) {
if (str1 == null || str2 == null) {
throw new IllegalArgumentException("Strings cannot be null");
}
return str1 + str2;
}
}
单元测试代码:StringUtilTest.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class StringUtilTest {
@Before
public void setUp() {
System.out.println("Setting up test environment...");
}
@After
public void tearDown() {
System.out.println("Cleaning up test environment...");
}
@Test
public void testReverse() {
String input = "hello";
String expected = "olleh";
assertEquals("Reverse method failed", expected, StringUtil.reverse(input));
}
@Test
public void testConcatenate() {
String str1 = "hello";
String str2 = "world";
String expected = "helloworld";
assertEquals("Concatenate method failed", expected, StringUtil.concatenate(str1, str2));
}
@Test
public void testReverseWithNull() {
assertThrows(IllegalArgumentException.class, () -> StringUtil.reverse(null));
}
@Test
public void testConcatenateWithNull() {
assertThrows(IllegalArgumentException.class, () -> StringUtil.concatenate("hello", null));
}
}
使用场景
- 持续集成:将单元测试集成到 CI/CD 流程中,自动验证代码质量。
- 重构保障:在重构代码时,通过单元测试快速验证功能是否被破坏。
- Bug 修复:为修复的 Bug 编写单元测试,防止相同问题重复出现。
总结
单元测试是保障代码质量的关键工具。通过 JUnit,可以方便地验证方法行为、捕获异常,并提升代码的健壮性。在实际开发中,单元测试与自动化工具结合,能有效提高开发效率和代码稳定性。