trycatchtest.groovy

来自「Groovy动态语言 运行在JVM中的动态语言 可以方便的处理业务逻辑变化大的业」· GROOVY 代码 · 共 84 行

GROOVY
84
字号
class TryCatchTest extends GroovyTestCase {

    def exceptionCalled
    def finallyCalled
	
    void testTryCatch() {
        try {
            failingMethod()
        }
        catch (AssertionError e) {
            onException(e)
        }
        finally {
            onFinally()
        }
        afterTryCatch()
        assert exceptionCalled , "should have invoked the catch clause"
        assert finallyCalled , "should have invoked the finally clause"
        println("After try/catch")
     }


     void testTryFinally() {
         Boolean touched = false;
         
         try {
         }
         finally {
             touched = true;
         }

         assert touched , "finally not called with empty try"
     }



     void testWorkingMethod() {
         /** @todo causes inconsistent stack height
          assert exceptionCalled == false , "should not invoked the catch clause"
          */
         
         try {
	    	 workingMethod()
	     }
	     catch (AssertionError e) {
		     onException(e)
	     }
	     finally {
		     onFinally()
	     }
	     assert exceptionCalled == false , "should not invoked the catch clause"
	     assert finallyCalled , "should have invoked the finally clause"
	     println("After try/catch")
    }
    
    void failingMethod() {
        assert false , "Failing on purpose"
	}
	
    void workingMethod() {
        assert true , "Should never fail"
    }
    
    void onException(e) {
	    assert e != null
	    exceptionCalled = true
	}
	
    void onFinally() {
        finallyCalled = true
	}

    void afterTryCatch() {
        assert exceptionCalled , "should have invoked the catch clause"        
        assert finallyCalled , "should have invoked the finally clause"
        println("After try/catch")
    }
    
    protected void setUp() {
        exceptionCalled = false
        finallyCalled = false
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?