简体   繁体   中英

How to avoid UnsupportedEncodingException in Junit

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

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);
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM