0

I would like to know how I can write a unit test to get the catch block covered for the following method. The FOM.create(data) is a static method.

  public String getValue(Data data) {
      try {
          return FOM.create(data);
      } catch (UnsupportedEncodingException e) {
          log.error("An error occured while creating data", e);
          throw new IllegalStateException(e);
      }
  }

Currently this is my unit test but it doesn't hit the catch block:

@Test (expected = UnsupportedEncodingException.class)
public void shouldThrowUnsupportedEncodingException() {
    doThrow(UnsupportedEncodingException.class).when(dataService).getUpdatedJWTToken(any(Data.class));
    try {
        dataService.getValue(data);
    }catch (IllegalStateException e) {
        verify(log).error(eq("An error occured while creating data"), any(UnsupportedEncodingException.class));
        throw e;
    }
}
Lean
  • 1
  • 1
  • 2

2 Answers2

0

You can check throwable exception if exception does not caught before unit test. In your case you cant check UnsupportedEncodingException but can check IllegalStateException.

Unit test must looks like:

@Test (expected = IllegalStateException.class)
public void shouldThrowIllegalStateException() {      
    dataService.getValue(data);
}

if you wanna to check UnsupportedEncodingException you must testing FOM.create(data) method

Bukharov Sergey
  • 9,767
  • 5
  • 39
  • 54
0

You can use JUnits exception rule like this:

 public class SimpleExpectedExceptionTest {
     @Rule
     public ExpectedException thrown= ExpectedException.none();

     @Test
     public void throwsExceptionWithSpecificType() {
         thrown.expect(NullPointerException.class);
         thrown.expectMessage("Substring in Exception message");
         throw new NullPointerException();
     }
 }
Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51