Search code examples
javaunit-testingmockingmockito

How to mock a String using mockito?


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 achieve that using the following code:

String nonEncodedString = mock(String.class);
when(nonEncodedString.getBytes(anyString())).thenThrow(new UnsupportedEncodingException("Parsing error."));

The problem is that when I run my test case I get a MockitoException that says that I can't mock a java.lang.String class.

Is there a way to mock a String object using mockito or, alternatively, a way to make my String object throw an UnsupportedEncodingException when I call the getBytes method?


Here are more details to illustrate the problem:

This is the class that I want to test:

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.
            ...
        }
    }
}

This is my testing class (I'm using JUnit 4 and 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);
    }
}

Solution

  • 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.