java如何单元测试
Java 单元测试方法
使用 JUnit 框架
JUnit 是 Java 最流行的单元测试框架,最新版本为 JUnit 5(Jupiter)。需在项目中添加依赖(Maven 示例):
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
测试类示例:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CalculatorTest {
@Test
void testAdd() {
Calculator calc = new Calculator();
assertEquals(5, calc.add(2, 3));
}
}
Mockito 模拟对象
对于依赖外部服务的测试,使用 Mockito 创建模拟对象:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.5.1</version>
<scope>test</scope>
</dependency>
测试示例:
import static org.mockito.Mockito.*;
@Test
void testUserService() {
UserRepository mockRepo = mock(UserRepository.class);
when(mockRepo.findById(1L)).thenReturn(new User(1, "Alice"));
UserService service = new UserService(mockRepo);
User user = service.getUser(1L);
assertEquals("Alice", user.getName());
}
测试覆盖率工具
JaCoCo 可生成测试覆盖率报告,Maven 配置:
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<executions>
<execution>
<goals><goal>prepare-agent</goal></goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals><goal>report</goal></goals>
</execution>
</executions>
</plugin>
执行 mvn test 后会在 target/site/jacoco 生成 HTML 报告。
参数化测试
JUnit 5 支持多参数测试:
@ParameterizedTest
@ValueSource(ints = {1, 3, 5})
void testIsOdd(int number) {
assertTrue(number % 2 != 0);
}
测试生命周期注解
@BeforeEach: 每个测试方法前执行@AfterEach: 每个测试方法后执行@BeforeAll: 所有测试前执行(静态方法)@AfterAll: 所有测试后执行(静态方法)
AssertJ 断言库
提供更流畅的断言语法:
import static org.assertj.core.api.Assertions.*;
assertThat(user.getName()).startsWith("A").endsWith("e");
assertThat(list).containsExactly(1, 2, 3);
集成测试与单元测试
单元测试应隔离依赖,对于需要数据库等真实环境的测试,使用 @SpringBootTest 等集成测试注解,但执行速度较慢,建议分开管理。







