java - Junit:期望 / assertThrows 不起作用
问题描述
我的代码在哪里抛出异常:(假设它是 UserService.generate() )
try {
UrlDecoder.decode(someString); // invalid somestring here
...
} catch (UnsupportedEncodingException | RuntimeException e) {
customLogger("Exception message here");
}
我如何尝试在测试中捕获此异常:
@Test(expected = IllegalArgumentExeception.class)
public void test() {
UserService u = new UserService();
u.generate("invalidString");
}
结果:
//info logs here
java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "^I"
//Exception details here
java.lang.AssertionError: Expected exception: java.lang.IllegalArgumentException
解决方案
URLDecoder.decode(someString)的javadoc声明它不会抛出异常。我相信您打算使用 URLDecoder.decode(someString, StandardCharsets.UTF_8.name())。但是仅当您要求的字符集不受支持时才会抛出 Unsupported encoding 异常。这是一种可以让异常被抛出的方法,以及一种检查它是否被抛出的方法。这个答案使用Mockito,这是一个非常强大的模拟框架。
import org.mockito.Mockito;
public class UserService {
public void generate(String someString, String encoding) {
try {
URLDecoder.decode(someString, encoding);
} catch (UnsupportedEncodingException e) {
customLogger("Exception message here");
}
}
public void customLogger(String string) {
// Do something
}
}
@Test
public void testThrowsOnBadEncoding() {
UserService u = Mockito.spy(new UserService());
u.generate("vl%23%46", "unknown");
Mockito.verify(u).customLogger("Exception message here");
}
推荐阅读
- node.js - 安装新组件后删除 Angular 组件
- dart - 如何突出显示所选卡片的边框?
- python - 优化大tick数据生成数据的功能
- c# - Xamarin Android 获取 imageuri?
- c# - C# 中的 -= 运算符
- javascript - JavaScript 在控制台中更改构造函数名称
- prestashop-1.7 - 为生日表单覆盖 CustomerFormatter.php
- tensorflow - TypeError: __init__() 得到了一个意外的关键字参数“重复”
- jquery - 产品 ID 从 ajax 传递到 servlet,但不知何故值为 null
- android - Firebase 数据上传