Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android org.json.JSONObject returns null in unit tests

I have a problem connected with parsing JSON while testing functionality using JUnit. I want to test my parsing logic. While I am executing test case I receive an error message:

java.lang.RuntimeException: Method getString in org.json.JSONObject not mocked

I have read that there is a need to provide additional dependency to tests because of org.json is provided with Android SDK, so I have put into gradle:

testImplementation 'org.json:json:20180130'

Unfortunately, this has no effect. Error occurs when I execute function getString() on JSON object:

json.getString(JSON_TYPE)

Have anyone had a similar problem and know how to deal with it?

//EDIT

here is the function (shortened form) that is responsible for parsing and causes the problem:

fun parse(jsonString: String) {
   val json = JSONObject(jsonString)
   val type = json.getString(JSON_TYPE) //here occurs an error
   val id = json.getString(JSON_ID)
}
like image 555
Patryk Jabłoński Avatar asked Oct 27 '25 04:10

Patryk Jabłoński


1 Answers

You need to add the following to the build.gradle: The code below works for me, When I need to parse Json in Test

android {
  // ...
  testOptions { 
    unitTests.returnDefaultValues = true
  }
}

and

dependencies {
//...
    testImplementation 'org.json:json:20180813'
}
like image 87
Thiago Avatar answered Oct 30 '25 14:10

Thiago



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!