Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);     } } 
like image 307
Alceu Costa Avatar asked Jul 03 '09 12:07

Alceu Costa


People also ask

How do you mock a String?

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

Can we mock interface using Mockito?

The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called.

How do you make a mock object in JUnit example?

We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.


1 Answers

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.

like image 148
Peter Avatar answered Sep 21 '22 04:09

Peter