java如何写测试类
编写Java测试类的基本方法
Java测试类通常使用JUnit框架进行编写,以下是创建测试类的详细步骤:
创建测试类文件
在项目的src/test/java目录下新建一个与被测类同包名的类,命名规范为被测试类名+Test。例如被测类是Calculator,则测试类命名为CalculatorTest。
添加JUnit依赖 在Maven项目中,pom.xml需包含以下依赖:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
编写测试方法
基本测试方法结构:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
assertEquals(5, calc.add(2, 3));
}
}
常用断言方法:
assertEquals(expected, actual):验证期望值与实际值相等assertTrue(condition):验证条件为真assertNull(object):验证对象为nullassertThrows(exceptionType, executable):验证抛出指定异常
测试生命周期注解
JUnit5提供以下常用注解控制测试生命周期:
@BeforeEach
void setUp() {
// 每个测试方法前执行
}
@AfterEach
void tearDown() {
// 每个测试方法后执行
}
@BeforeAll
static void initAll() {
// 所有测试方法前执行一次
}
@AfterAll
static void tearDownAll() {
// 所有测试方法后执行一次
}
参数化测试
使用@ParameterizedTest实现多参数测试:
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testIsPositive(int number) {
assertTrue(number > 0);
}
Mock测试
使用Mockito进行模拟对象测试:
@ExtendWith(MockitoExtension.class)
class ServiceTest {
@Mock
private Dependency dependency;
@InjectMocks
private Service service;
@Test
void testMethod() {
when(dependency.someMethod()).thenReturn("mocked");
assertEquals("mocked", service.useDependency());
}
}
测试覆盖率检查
使用JaCoCo插件检查测试覆盖率,在pom.xml中添加:
<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>
运行测试后可在target/site/jacoco目录查看覆盖率报告。







