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); } }
String nonEncodedString = mock(String. class); when(nonEncodedString. getBytes(anyString())). thenThrow(new UnsupportedEncodingException("Parsing error."));
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With