[Android] 使用Android Test 進行測試卻無法打印Log怎麼辦 [Android] 使用Android Test 進行測試卻無法打印Log怎麼辦

[Android] 使用Android Test 進行測試卻無法打印Log怎麼辦

問題

在Android Test中進行測試還是很方便的,但有時也會不太方便。比如我有很多數據,檢測一個函數是否工作正常,放到一個數組中遍歷測試的,當出現問題時,我不知道是哪個數據處理出現了問題。

如果你想要使用Log的功能,發現毫無用處,找不到你的日誌在哪裏。
這個日誌應該不是由你當前的軟件打印的,而是包名爲your_original_package_name.test 的軟件打印的,可能跟這個有關吧。反正就是Android Studio 沒有展示日誌。

思考

雖然日誌無法打印,但是出現錯誤時還是會有提示的,長得好像Exception(其實不是,後面會說)。

既然是個“異常”,那就捕獲它吧。然後換成自己的異常,在這個異常中添加一些調試信息,甚至自己做一個異常類不就好了。

    try {
        //...
    } catch (Exception e) {
        //...
    }

但是這樣其實不能夠捕獲異常,仔細看那個錯誤,是java.lang.AssertionError,是Error 而不是Exception

谷歌的文檔寫的是

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

Error 是一個Throwable 的子類,標識一個嚴重錯誤,一個resonable application 不應該嘗試去捕獲它。

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.

上面說一個應用不應該捕獲Error 但是我不管,我就要這麼幹。反正運行這段代碼的也不是一個resonable application

try {
    assertFalse(...);
} catch (AssertionError ignored) {
    throw new AssertionError("hello world");
}

這樣就可以正常調試了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章