getBytes()
String オブジェクトのメソッドを呼び出して UnsupportedEncodingException を取得するテスト シナリオをシミュレートする必要があります。
私は次のコードを使用してそれを達成しようとしました:
String nonEncodedString = mock(String.class);
when(nonEncodedString.getBytes(anyString())).thenThrow(new UnsupportedEncodingException("Parsing error."));
問題は、テスト ケースを実行すると、java.lang.String クラスをモックできないことを示す MockitoException が発生することです。
mockito を使用して String オブジェクトをモックする方法、または getBytes メソッドを呼び出したときに String オブジェクトに UnsupportedEncodingException をスローさせる方法はありますか?
問題を説明する詳細は次のとおりです。
これは私がテストしたいクラスです:
public final class A {
public static String f(String str){
try {
return new String(str.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// This is the catch block that I want to exercise.
...
}
}
}
これは私のテストクラスです (私は JUnit 4 と mockito を使用しています):
public class TestA {
@Test(expected=UnsupportedEncodingException.class)
public void test(){
String aString = mock(String.class);
when(nonEncodedString.getBytes(anyString())).thenThrow(new UnsupportedEncodingException("Parsing error."));
A.f(aString);
}
}