How to mock a String using mockito?

Posted by Alceu Costa on Stack Overflow See other posts from Stack Overflow or by Alceu Costa
Published on 2009-07-03T12:55:34Z Indexed on 2010/05/21 22:50 UTC
Read the original article Hit count: 238

Filed under:
|
|
|

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);
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about unit-testing