I have the following implementation as follows:
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 "";
}
I have tried to write junit test for the implementation, the test did not fail but was not able to throw the exception as intended.
@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
}
I would greatly appreciate any form of help or sharing of knowledge if you have encountered the following issue previously. Thank you!
You should use the @PrepareForTest({URLEncoder.class}) annotation on the class level to tell PowerMockito that we need to manipulate byte codes of the URLEncoder class.
If you don't do that, there is no way PowerMockito is able to mock a static method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.