How to avoid UnsupportedEncodingException in Junit

3.1k views Asked by At

I have the following code which needs the UnsupportedEncodingException to be handled by try-catch or throws declaration but I want to use neither of them.

  @Test
  public void serializeAndDeserializeUTF8StringValueExpectingEqual() {
    String stringValue = "\u0048\u0065\u006C\u006C\u006F";
    String deserializedStringValue = serialzeAndDeserializeStringValue(stringValue);
    assertThat(deserializedStringValue.getBytes("UTF-8")).isEqualTo(stringValue.getBytes("UTF-8"));
  }

For example I avoided NullPointerException by using assertThatNullPointerException().isThrownBy as following

  @Test
  public void serializeAndDeserializeNullStringValueExpectingEqual() {
    String stringValue = null;
    assertThatNullPointerException()
        .isThrownBy(() -> OutputStreamUtil.serializeString(stringValue, oStream));
  }

Is there any way to avoid using try-catch or throws declaration for UnsupportedEncodingException

2

There are 2 answers

0
Piotr Rogowski On BEST ANSWER

Maybe should try like this:

 @Test
 public void serializeAndDeserializeUTF8StringValueExpectingEqual()  {
        String stringValue = "\u0048\u0065\u006C\u006C\u006F";
        String deserializedStringValue = new String(stringValue);

        Throwable thrown = catchThrowable(() -> deserializedStringValue.getBytes("UTF-8"));

        assertThat(thrown).isExactlyInstanceOf(UnsupportedEncodingException.class);
    }
0
AndrewG On

If you are using Junit 4 and up you could use:

assertThrows(UnsupportedEncodingException.class, () -> {
    nameOfObjectThatThrows.nameOfMethodThatThrows();
});

This is similar to how you bypassed your null pointer with basically asserting that it was thrown from a specific method.