【问题标题】:Using try-catch to write unit tests使用 try-catch 编写单元测试
【发布时间】:2021-09-30 06:22:47
【问题描述】:

我可以使用 try-catch 为以下代码编写单元测试吗?

if (currentAZ == null) {               
   throw new IllegalStateException("Cannot fetch Current AZ information.");         
}

【问题讨论】:

  • 为什么需要一个 try catch 来测试它?

标签: java unit-testing testing


【解决方案1】:

是的,你可以使用 Junit4 类似的东西:

    @org.junit.Test(expected = IllegalStateException.class)
    public void testMethod() {
        try {
            callMethod(null);
        } catch (Exception e) {
            org.assertj.core.api.Assertions.assertThat(e).hasMessageContaining("AZ information");
            throw e;
        }
    }

但最好使用 Junit5:

    @org.junit.jupiter.api.Test
    public void testMethod() {
        org.assertj.core.api.Assertions.assertThatThrownBy(() -> callMethod(null)).isInstanceOf(IllegalStateException.class)
                .hasMessageContaining("AZ information");
    }

【讨论】:

  • 那里的try catch有什么用?最好使用规则而不是污染你的测试代码
猜你喜欢
  • 2020-02-24
  • 2020-10-13
  • 2015-06-15
  • 1970-01-01
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
  • 2019-10-20
  • 2018-10-29
相关资源
最近更新 更多