Hi, I encountered strange issues with `JSONObject`...
# announcements
j
Hi, I encountered strange issues with
JSONObject
in Android. Can anyone help me, please?
Copy code
@Test
fun `create JSON, must not be empty or null`() {
    val json = JSONObject()
    json.put("name", "value")

    assertNotNull(json)
    assertEquals("value",json.get("name"))
}
Running above test fails, but I believe it should not. What’s wrong with
JSONObject
?
e
I think
json.get("name")
does not give you a string but a
JSONObject
or sth
j
That’s definitely not a problem, because the object returned by
json.get("name")
returns null anyway
g
This test passes for me
j
Thank you for feedback. Will check that outside unit tests.
Guess it’ll be something related to Android. I tried to turn off
Copy code
testOptions {
        unitTests.returnDefaultValues = true
    }
g
oh, Android, yeah I test on pure Java project
I suppose this is because you use org.json.JSONObject
and this is a part of the Android Framework
so you cannot use it in unit tests without mocking
j
Aaah, ok. Thank you :))
g
You probably use
Copy code
unitTests.returnDefaultValues = true
so instead of throwing exception you got null value as result
if
returnDefaultValues = true
in your project, my advice to disable it, otherwise you will get a lot of such hard to understand problems
to test JSONObject maybe make sense to add
org.json:json
to test dependencies and use it instead of platform one, but be careful, version of this library can be different on Android Framewrok
j
Yeah, I know using
returnDefaultValues = true
is not recommended, I just wanted to quickly test something with OkHttp
g
Hm? OkHttp can be used without mocking, this is not a part of Android Framework and not Android library at all, you can use it without problem for unit tests
j
You’re right, but you cannot pass JSONObjects there then without mocking.
g
Why do you need this on okhttp?
You can serialize/deserialize json using any json library in your tests
j
I wanted to create json, sign it and post it via okHttp
But there’s probably no reason to do that. As long as it can add
Signature
header (it can) and can post json (tested elsewhere), it must work 🙂
g
also, don’t forget about old good strings:
Copy code
"""{"my":"json", "object": []}"""
👍 1
j
Will do, thanks. The reason why I went in a more like “integration way” was that I’m still getting used to Kotlin and testing what could possible be issue and what not