zoukankan      html  css  js  c++  java
  • JUnit 异常测试

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

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

  • 相关阅读:
    ActiveX Demo
    VC6 DLL exports
    进程间通信:剪切板
    Hook编程2:全局钩子
    Cookieless Session In WebService
    Report predicts possible PS3 launch delay
    原来是PS过的
    Xbox360日本卖不动.历代主机首周销量对比
    DirectX SDK (February 2006)
    vbo的速度问题,没有想象中快
  • 原文地址:https://www.cnblogs.com/qulianqing/p/12622891.html
Copyright © 2011-2022 走看看