首页 > 其他 > 详细

JUnit 异常测试

时间:2020-04-02 22:56:57      阅读:58      评论:0      收藏:0      [点我收藏+]

JUnit 异常测试

  1. 上古写法
    @Test
    void name() {
        boolean hasException = false;
        String exceptionMessage = null;
        try {
            check();
        } catch (RuntimeException e) {
            hasException = true;
            exceptionMessage = e.getMessage();
        }
        assertEquals("runtime", exceptionMessage);
        assertTrue(hasException);
    }

    void check() {
        throw new RuntimeException("runtime");
    }
  1. 普通写法(易错的)
    check message 和异常类型
   @Test
   void name() {
      assertThrows(RuntimeException.class, () -> check(), "aaa");
   }

   void check() {
       throw new RuntimeException("runtime");
   }

这个测试我们发现异常message 不对但是测试也能过。
扒一扒源码
技术分享图片

发现消费message 居然测试不是异常的消息,而是异常不是期待的,和没有异常的情况去消费的。
2.1 普通写法

   @Test
    void name() {
        final RuntimeException runtimeException = assertThrows(RuntimeException.class, () -> check());
        assertEquals("runtime", runtimeException.getMessage());
    }

    void check() {
        throw new RuntimeException("runtime");
    }

3.流式写法

     @Test
    void name() {
        assertThatThrownBy(() -> check())
            .isInstanceOf(RuntimeException.class)
            .hasMessage("runtime");
    }

    void check() {
        throw new RuntimeException("runtime");
    }

个人认为流式写法目前的认知范围内是最优雅的。

JUnit 异常测试

原文:https://www.cnblogs.com/qulianqing/p/12622891.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!