java如何写单元测试
单元测试的基本概念
单元测试是针对代码中最小可测试单元(如方法、类)的验证过程,通常使用测试框架(如JUnit)编写。Java中常用JUnit 5作为测试框架,需通过Maven或Gradle引入依赖。
依赖配置
Maven项目的pom.xml中添加JUnit 5依赖:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
Gradle项目的build.gradle中添加:
testImplementation 'org.junit.jupiter:junit-jupiter:5.8.2'
测试类与测试方法
测试类需使用@Test注解标记测试方法。示例:

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calculator = new Calculator();
assertEquals(5, calculator.add(2, 3));
}
}
常用断言方法
assertEquals(expected, actual):验证期望值与实际值相等。assertTrue(condition):验证条件为真。assertNull(object):验证对象为null。assertThrows(Exception.class, () -> { ... }):验证代码块抛出指定异常。
测试生命周期注解
@BeforeEach:每个测试方法前执行,用于初始化。@AfterEach:每个测试方法后执行,用于清理。@BeforeAll:所有测试方法前执行(静态方法)。@AfterAll:所有测试方法后执行(静态方法)。
示例:
import org.junit.jupiter.api.*;
public class LifecycleTest {
@BeforeAll
static void setupAll() {
System.out.println("Before all tests");
}
@BeforeEach
void setupEach() {
System.out.println("Before each test");
}
@Test
void test1() {
System.out.println("Test 1");
}
@AfterEach
void tearDownEach() {
System.out.println("After each test");
}
@AfterAll
static void tearDownAll() {
System.out.println("After all tests");
}
}
参数化测试
使用@ParameterizedTest和@ValueSource等注解实现多参数测试:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class ParameterizedTestExample {
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testWithValues(int value) {
assertTrue(value > 0);
}
}
Mock对象(使用Mockito)
模拟依赖对象的行为,需额外引入Mockito依赖:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.5.1</version>
<scope>test</scope>
</dependency>
示例:
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;
public class UserServiceTest {
@Test
public void testGetUser() {
UserRepository mockRepo = mock(UserRepository.class);
when(mockRepo.findById(1L)).thenReturn(new User(1L, "Alice"));
UserService service = new UserService(mockRepo);
User user = service.getUser(1L);
assertEquals("Alice", user.getName());
verify(mockRepo).findById(1L);
}
}
测试覆盖率
使用工具如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>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
运行mvn test后,报告生成在target/site/jacoco/index.html。






