Android Studio 2.0 Beta5中使用本機單元測試時,遇到使用JSONObject代碼時拋出異常:
比如:JSONObject jsonObject = new JSONObject();
報異常:java.lang.RuntimeException: Method put in org.json.JSONObject not mocked. See https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support for details.
但是將測試代碼放到設備AndroidTest中,使用JSONObject代碼時無異常。
原來,JSON包含在Android SDK中,JUnit單元測試無法使用,會拋異常;但可以在AndroidTest中使用,如果要在Junit中使用,需要在App或Library項目的build.gradle中添加依賴:
testCompile files('libs/json.jar')
其實上面異常中google給了鏈接說明,可惜我大天朝子民已習慣忽略點擊那個不可能訪問的站點。