I need to simulate a test scenario in which I call the getBytes()
method of a String object and I get an UnsupportedEncodingException.
I have tried to achie
If you can use JMockit, look at Rogério answer.
If and only if your goal is to get code coverage but not actually simulate what missing UTF-8 would look like at runtime you can do the following (and that you can't or don't want to use JMockit):
public static String f(String str){
return f(str, "UTF-8");
}
// package private for example
static String f(String str, String charsetName){
try {
return new String(str.getBytes(charsetName));
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Unsupported encoding: " + charsetName, e);
}
}
public class TestA {
@Test(expected=IllegalArgumentException.class)
public void testInvalid(){
A.f(str, "This is not the encoding you are looking for!");
}
@Test
public void testNormal(){
// TODO do the normal tests with the method taking only 1 parameter
}
}