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
Have you tried passing an invalid charsetName to getBytes(String)?
You could implement a helper method to get the charsetName, and override that method within your test to a nonsense value.
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.
It is a project requirement that the unit tests coverage percentage must but higher than a given value. To achieve such percentage of coverage the tests must cover the catch block relative to the UnsupportedEncodingException.
What is that given coverage target? Some people would say that shooting for 100% coverage isn't always a good idea.
Besides, that's no way to test whether or not a catch block was exercised. The right way is to write a method that causes the exception to be thrown and make observation of the exception being thrown the success criterion. You do this with JUnit's @Test annotation by adding the "expected" value:
@Test(expected=IndexOutOfBoundsException.class) public void outOfBounds() {
new ArrayList<Object>().get(1);
}