简体   繁体   English

在Kotlin JUnit 4 Test中无法捕获异常

[英]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. 我想检查一个String是否在单元测试中具有有效的JSON格式。

To do this, I try creating a new JSONObject from the string and catching any possible Exceptions that can be thrown. 为此,我尝试从字符串创建一个新的JSONObject并捕获可能引发的任何异常。

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. 在调试器中对相同的表达式求值表明应该抛出一个Exception,但永远不要将其捕获。

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 我在一个Android Studio Android项目中使用JUnit 4.12hamcrest-library:1.3Kotlin 1.2.31

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. 编辑:如此处指出https://stackoverflow.com/a/32822468/3708094 JSONObject是android框架的一部分,并且在单元测试中不可用。 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. 疑似问题的根源是JSONObject是Android系统库的一部分。

For me the solution was to manually add JSONObject in gradle to the testImplementation 对我来说,解决方案是在gradle中手动将JSONObject添加到testImplementation

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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