为 java 中的异常编写单元测试:使用 @test(expected = exception.class) 注解:告诉 junit 预期抛出特定异常。使用 try-catch 块:捕获异常并使用 asserttrue() 进行具体检查。使用 mockito 验证抛出的异常:使用 verify() 方法确保抛出了预期的异常。

如何为 Java 中的异常编写单元测试
实战案例:
假设我们有一个名为 UserService 的类,其中有一个方法 createUser()。该方法可能抛出一个 UserAlreadyExistsException,如果另一个用户已被赋予相同的用户名。
立即学习“Java免费学习笔记(深入)”;
使用 @Test(expected = Exception.class) 进行测试:
最简单的方法是使用 @Test(expected = Exception.class) 注解。这将告诉 JUnit 运行测试时期望抛出给定的异常。
@Test(expected = UserAlreadyExistsException.class)
public void testCreateUser_whenUserExists() {
// Setup the test...
userService.createUser("existingUser");
}使用 try-catch 块进行测试:
另一个方法是使用 try-catch 块。这允许你在发生异常时使用 assertTrue() 进行更具体的检查。
@Test
public void testCreateUser_whenUserExists() {
// Setup the test...
try {
userService.createUser("existingUser");
fail("Expected UserAlreadyExistsException");
} catch (UserAlreadyExistsException e) {
assertTrue("The exception message should contain the user name", e.getMessage().contains("existingUser"));
}
}Mockito 验证抛出的异常:
如果你使用的是 Mockito,你可以使用 verify() 方法来验证是否抛出了预期的异常。
@Test
public void testCreateUser_whenUserExists() {
// Mock the UserService...
doThrow(new UserAlreadyExistsException("existingUser"))
.when(userService)
.createUser("existingUser");
// Run the test...
verify(userService).createUser("existingUser");
}注意:
@Test(expected = Exception.class) 时,如果你在测试方法中抛出了任何其他异常,则测试都会失败。fail() 来阻止测试继续执行。assertThat() 方法来进行更具体的检查。以上就是如何为 Java 中的异常编写单元测试?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号