How to mock a String using mockito?
The problem is the String
class in Java is marked as final, so you cannot mock is using traditional mocking frameworks. According to the Mockito FAQ, this is a limitation of that framework as well.
If all you are going to do in your catch block is throw a runtime exception then you can save yourself some typing by just using a Charset object to specify your character set name.
public final class A{
public static String f(String str){
return new String(str.getBytes(Charset.forName("UTF-8")));
}
}
This way you aren't catching an exception that will never happen just because the compiler tells you to.
How about just creating a String
with a bad encoding name? See
public String(byte bytes[], int offset, int length, String charsetName)
Mocking String
is almost certainly a bad idea.