在 IntelliJ IDEA 中进行单元测试的完整流程
一 环境准备与依赖配置
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
testImplementation 'org.junit.jupiter:junit-jupiter:5.8.2'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2'
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
testImplementation 'junit:junit:4.13.2'
二 创建测试类与编写测试方法
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
private final Calculator calculator = new Calculator();
@Test
void add_shouldReturnSum() {
assertEquals(5, calculator.add(2, 3));
}
@Test
void divide_shouldThrowWhenDivideByZero() {
assertThrows(IllegalArgumentException.class, () -> calculator.divide(1, 0));
}
}
三 运行与调试测试
四 进阶用法
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class CalculatorTest {
private final Calculator calculator = new Calculator();
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void add_shouldReturnInputPlusOne(int n) {
assertEquals(n + 1, calculator.add(n, 1));
}
}
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
class UserServiceTest {
@Test
void shouldReturnUserWhenFound() {
var repo = mock(UserRepository.class);
when(repo.findById(1L)).thenReturn(new User(1L, "Alice"));
UserService service = new UserService(repo);
var user = service.findById(1L);
assertEquals("Alice", user.getName());
}
}
依赖示例(Maven,JUnit 4 + Mockito 3):<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.11.2</version>
<scope>test</scope>
</dependency>
五 常见问题与排查
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。