java test 如何测试
测试 Java 代码的方法
Java 测试通常分为单元测试、集成测试和端到端测试,常用工具包括 JUnit、TestNG、Mockito 等。以下是具体方法和工具的使用说明。
单元测试
单元测试用于验证单个方法或类的行为是否符合预期。JUnit 是最常用的单元测试框架。
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calculator = new Calculator();
assertEquals(5, calculator.add(2, 3));
}
}
集成测试
集成测试用于验证多个组件之间的交互。Spring Boot 提供 @SpringBootTest 注解支持集成测试。
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.junit.jupiter.api.Test;
@SpringBootTest
public class UserServiceIntegrationTest {
@Autowired
private UserService userService;
@Test
public void testCreateUser() {
User user = userService.createUser("testUser");
assertNotNull(user);
}
}
Mock 测试
Mock 测试用于模拟依赖对象的行为,常用工具为 Mockito。
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
public class OrderServiceTest {
@Test
public void testPlaceOrder() {
PaymentService mockPayment = mock(PaymentService.class);
when(mockPayment.process(anyDouble())).thenReturn(true);
OrderService orderService = new OrderService(mockPayment);
assertTrue(orderService.placeOrder(100.0));
}
}
测试覆盖率
使用 JaCoCo 或 Cobertura 工具生成测试覆盖率报告。在 Maven 中配置 JaCoCo:
<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>
运行 mvn test 后,覆盖率报告会生成在 target/site/jacoco/ 目录下。
参数化测试
JUnit 5 支持参数化测试,通过 @ParameterizedTest 注解实现。
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class StringTest {
@ParameterizedTest
@ValueSource(strings = {"racecar", "radar", "level"})
public void testPalindrome(String word) {
assertTrue(StringUtils.isPalindrome(word));
}
}
测试异常
使用 assertThrows 验证代码是否抛出预期异常。
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ExceptionTest {
@Test
public void testDivideByZero() {
Calculator calculator = new Calculator();
assertThrows(ArithmeticException.class, () -> calculator.divide(1, 0));
}
}
性能测试
JMH 是 Java 微基准测试工具,适合测量方法执行时间。

import org.openjdk.jmh.annotations.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MyBenchmark {
@Benchmark
public void testMethod() {
// 被测代码
}
}
通过以上方法,可以全面覆盖 Java 代码的测试需求。根据项目实际情况选择合适的工具和策略。






