猿问

如何避免 Junit 中的 UnsupportedEncodingException

我有以下代码需要UnsupportedEncodingException通过 try-catch 或 throws 声明来处理,但我不想使用它们。


  @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"));

  }

例如我避免NullPointerException使用assertThatNullPointerException().isThrownBy如下


  @Test

  public void serializeAndDeserializeNullStringValueExpectingEqual() {

    String stringValue = null;

    assertThatNullPointerException()

        .isThrownBy(() -> OutputStreamUtil.serializeString(stringValue, oStream));

  }

有什么方法可以避免使用 try-catch 或 throws 声明 UnsupportedEncodingException


慕姐8265434
浏览 199回答 2
2回答

慕码人2483693

也许应该这样尝试: @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);    }

慕森王

如果您使用的是 Junit 4 及更高版本,则可以使用:assertThrows(UnsupportedEncodingException.class, () -> {    nameOfObjectThatThrows.nameOfMethodThatThrows();});这类似于您绕过空指针的方式,基本上断言它是从特定方法抛出的。
随时随地看视频慕课网APP

相关分类

Java
我要回答