I know that this question is asked hundreds of time, I've checked more than 30 answer and none worked for me.
I'm running a unit test in android studio using Kotlin. I'm trying to build a JSONObject
using a String
.
The method I'm using to build a simple json object is always throwing Cannot evaluate org.json.JSONObject.toString()
.
The string I'm using definitely have a valid Json format.
Is this a bug in android or what??
Here's the method I'm using:
fun createTaskJson(): JSONObject {
val jsonString =
"{\"id\":138,\"title\":\"G0102-025\",\"type\":\"New Land Evaluation\",\"taskCreationDate\":\"28/01/2020\",\"taskDeliveryDate\":\"02/02/2020\",\"taskCreationTime\":\"05:15 AM\"}"
val realJson = JSONObject(jsonString)
return realJson
}
UPDATE 1:
Please note that also creating an empty JSONObject
will throw the same error !!
UPDATE 2:
After checking the stacktrace, I've found the following error:
Method toString in org.json.JSONObject not mocked.
I've googled it and the solution was to add the following configuration into my build.gradle
file:
testOptions {
unitTests.returnDefaultValues = true
}
But adding this made the returned JSONObject
null instead of throwing an exception, even though my string is formatted correctly.