java语言如何测试
测试 Java 程序的常用方法
单元测试(Unit Testing)
使用 JUnit 框架编写测试用例,验证单个方法或类的功能。JUnit 5 是当前主流版本,支持注解驱动的测试。
示例代码:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CalculatorTest {
@Test
void testAdd() {
Calculator calc = new Calculator();
assertEquals(5, calc.add(2, 3));
}
}
集成测试(Integration Testing)
通过 TestNG 或 JUnit 结合 Spring Test 等框架,测试多个模块的交互。Spring Boot 提供 @SpringBootTest 注解启动完整上下文。
@SpringBootTest
public class UserServiceIntegrationTest {
@Autowired
private UserService userService;
@Test
void testUserCreation() {
User user = userService.createUser("test");
assertNotNull(user.getId());
}
}
Mock 测试
使用 Mockito 模拟依赖对象,隔离被测组件。适用于测试依赖外部服务(如数据库、API)的代码。
@Test
void testPaymentWithMock() {
PaymentGateway mockGateway = Mockito.mock(PaymentGateway.class);
when(mockGateway.process(anyDouble())).thenReturn(true);
PaymentProcessor processor = new PaymentProcessor(mockGateway);
assertTrue(processor.makePayment(100.0));
}
测试覆盖率分析
通过 JaCoCo 或 Cobertura 生成覆盖率报告,确保测试覆盖关键逻辑。Maven 项目中配置示例:
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.7</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>
性能测试
使用 JMH(Java Microbenchmark Harness)进行微基准测试,或 Apache JMeter 模拟高并发场景。JMH 示例:
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class MyBenchmark {
@Benchmark
public void testMethod() {
// 被测代码
}
}
持续集成中的测试
在 CI/CD 流程(如 Jenkins、GitHub Actions)中自动运行测试。GitHub Actions 配置示例:

- name: Run tests
run: mvn test
- name: Upload coverage
uses: codecov/codecov-action@v2






