我具有以下实现:
public String encodeString(String testString) {
try {
return URLEncoder.encode(testString, "UTF-8");
} catch (UnsupportedEncodingException e) { <= I want to test this exception but was not successful
log.error(ex.getMessage());
}
return "";
}
我尝试为实现编写junit测试,测试没有失败,但是无法按预期抛出异常。
@Test
public void testEncodeString_Exception() throws UnsupportedEncodingException {
// Setup
final String testString= "U+FFFD";
PowerMockito.mockStatic(URLEncoder.class);
PowerMockito.when(URLEncoder.encode(testString, "UTF-8")).thenThrow(UnsupportedEncodingException.class);
// Run the test
final String result = classInstance.encodeString(testString);
// Verify the results
}
如果您之前遇到以下问题,我将非常感谢任何形式的帮助或知识共享。谢谢!
您应使用@Test(expected=UnsupportedEncodingException.class)
而不是@Test
来验证结果>