简体   繁体   中英

Unable to catch exception in Kotlin JUnit 4 Test

I want to check if a String has a valid JSON format in a unit tests.

To do this, I try creating a new JSONObject from the string and catching any possible Exceptions that can be thrown.

However, when running the code below, no Exception is caught

@Test
fun checkFunctionWithStringToJSONTest() {
    val invalidJSON = "INVALIDJSON--"
    try {
        JSONObject(invalidJSON)
    } catch (ex: Exception) {
        try {
            JSONArray(invalidJSON)
        } catch (ex1: Exception) {
            assert(false)
        }
    }
    assert(true)
}

Evaluating the same expression in the debugger shows that an Exception should be thrown, but is never caught.

Why is this happening?

I'm Using JUnit 4.12 , hamcrest-library:1.3 and Kotlin 1.2.31 in an Android studio Android project

EDIT: As pointed out here https://stackoverflow.com/a/32822468/3708094 JSONObject is a part of the android framework and not available in Unit Tests. Most likely this is related to the cause of the question above.

Even if it is not available, no Exception is caught, but something is thrown according to the debuggers evaluate tool.

As suspected, the origin of the problem is with JSONObject being a part of the Android system libraries.

For me the solution was to manually add JSONObject in gradle to the testImplementation

dependencies {
    ...
   testImplementation 'org.json:json:20180130'
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM