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
From its documentation, JDave can't remove "final" modifiers from classes loaded by the bootstrap classloader. That includes all JRE classes (from java.lang, java.util, etc.).
A tool that does let you mock anything is JMockit.
With JMockit, your test can be written as:
import java.io.*;
import org.junit.*;
import mockit.*;
public final class ATest
{
@Test(expected = UnsupportedOperationException.class)
public void test() throws Exception
{
new Expectations()
{
@Mocked("getBytes")
String aString;
{
aString.getBytes(anyString);
result = new UnsupportedEncodingException("Parsing error.");
}
};
A.f("test");
}
}
assuming that the complete "A" class is:
import java.io.*;
public final class A
{
public static String f(String str)
{
try {
return new String(str.getBytes("UTF-8"));
}
catch (UnsupportedEncodingException e) {
throw new UnsupportedOperationException(e);
}
}
}
I actually executed this test in my machine. (Notice I wrapped the original checked exception in a runtime exception.)
I used partial mocking through @Mocked("getBytes")
to prevent JMockit from mocking everything in the java.lang.String
class (just imagine what that could cause).
Now, this test really is unnecessary, because "UTF-8" is a standard charset, required to be supported in all JREs. Therefore, in a production environment the catch block will never be executed.
The "need" or desire to cover the catch block is still valid, though. So, how to get rid of the test without reducing the coverage percentage? Here is my idea: insert a line with assert false;
as the first statement inside the catch block, and have the Code Coverage tool ignore the whole catch block when reporting coverage measures. This is one of my "TODO items" for JMockit Coverage. 8^)