0

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

brass monkey
  • 5,841
  • 10
  • 36
  • 61
Salem Masoud
  • 411
  • 11
  • 32

2 Answers2

2

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);
    }
Piotr Rogowski
  • 3,642
  • 19
  • 24
0

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.

AndrewG
  • 145
  • 1
  • 13