为 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) 时,如果你在测试方法中抛出了任何其他异常,则测试都会失败。
使用 try-catch 块时,确保在预期抛出异常时使用 fail() 来阻止测试继续执行。
对于复杂的异常,你可以使用 JUnit 的 assertThat() 方法来进行更具体的检查。
以上就是如何为 Java 中的异常编写单元测试?的详细内容,更多请关注php中文网其它相关文章!


BrianSab9 天前
发表在:南通速强批量添加水印专家 v1.83Эта статья для ознак...
Ronaldgag11 天前
发表在:11日17日,星期一,在这里每天60秒读懂世界!Free PHP Blockchain ...
NelsonBOT11 天前
发表在:11日16日,星期日,在这里每天60秒读懂世界!Free non-criminal in...
Darrenjhjhjhcunny14 天前
发表在:11日14日,星期五,在这里每天60秒读懂世界!Атака черной материи...
parifoot-rdc-7925 天前
发表在:laravel 找不到页面Votre guide <a href=...
Anya142Sa1 个月前
发表在:ASUS华硕A8N-SLI Deluxe主板BIOS 10110Hello friends! I c...
91资源网站长-冰晨1 个月前
发表在:广告合作123
FrankFAT1 个月前
发表在:10日14日,星期二,在这里每天60秒读懂世界!Big cocks of blacks ...
RichardGlymn1 个月前
发表在:Java webservice多个参数怎么调用https://t.me/win_1_c...
Thomasstolo1 个月前
发表在:Java webservice多个参数怎么调用https://t.me/s/Casin...