java如何写单元测试
使用JUnit框架编写单元测试
JUnit是Java最常用的单元测试框架,需在项目中引入依赖(Maven示例):
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
测试类需用@Test注解标记测试方法:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
assertEquals(5, calc.add(2, 3));
}
}
测试异常和超时
使用assertThrows验证异常,assertTimeout验证超时:
@Test
public void testDivideByZero() {
Calculator calc = new Calculator();
assertThrows(ArithmeticException.class, () -> calc.divide(1, 0));
}
@Test
public void testTimeout() {
assertTimeout(Duration.ofMillis(100), () -> Thread.sleep(50));
}
使用Mockito模拟依赖
当测试对象依赖外部服务时,可用Mockito创建模拟对象:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.5.1</version>
<scope>test</scope>
</dependency>
示例模拟数据库调用:
@Test
public void testUserService() {
UserRepository mockRepo = Mockito.mock(UserRepository.class);
Mockito.when(mockRepo.findById(1L)).thenReturn(new User(1L, "Alice"));
UserService service = new UserService(mockRepo);
assertEquals("Alice", service.getUserName(1L));
}
参数化测试
通过@ParameterizedTest实现多组数据测试:
@ParameterizedTest
@ValueSource(ints = {1, 3, 5})
public void testIsOdd(int number) {
assertTrue(number % 2 != 0);
}
测试生命周期注解
利用@BeforeEach和@AfterEach设置测试前后操作:
@BeforeEach
public void setup() {
// 初始化测试资源
}
@AfterEach
public void cleanup() {
// 释放资源
}
测试覆盖率工具
结合JaCoCo生成覆盖率报告(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>
</executions>
</plugin>
运行mvn test后,报告默认生成在target/site/jacoco/目录。







