【问题标题】:How to avoid UnsupportedEncodingException in Junit如何避免 Junit 中的 UnsupportedEncodingException
【发布时间】:2019-01-15 16:45:32
【问题描述】:

我有以下代码需要 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"));
  }

例如,我通过使用assertThatNullPointerException().isThrownBy 来避免NullPointerException,如下所示

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

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

【问题讨论】:

  • 您能分享一下避免抛出声明的原因吗?对我来说是显而易见的解决方案。

标签: java junit try-catch assertions throws


【解决方案1】:

也许应该这样尝试:

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

【讨论】:

    【解决方案2】:

    如果您使用的是 Junit 4 及更高版本,您可以使用:

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

    这类似于您绕过空指针的方式,基本上断言它是从特定方法抛出的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      • 1970-01-01
      • 2011-09-13
      • 2010-10-14
      相关资源
      最近更新 更多