Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONObject Unit Testing Always Null

Tags:

json

android

I have been looking at this for an hour and can't seem to see what's wrong.

JSONObject jsonResponse = new JSONObject();
jsonResponse.put("JSON", "hi");
String myString = jsonResponse.getString("JSON");
assertEquals("hi", myString); 

Result... (The entire method throws Throwable). I tried try/catch as well. Same result....

java.lang.AssertionError: 
Expected :hi
Actual   :null

This is the class I am using

public class ECUserTests(){

    @org.junit.Test
    public void testUserExists(){

        try{
            JSONObject jsonResponse = new JSONObject();
            jsonResponse.put("JSON", "Hello, World!");
            String myString = jsonResponse.getString("JSON");
            assertEquals("hi", myString);
        }catch(JSONException e){
            e.printStackTrace();
        }
like image 764
Kai Mou Avatar asked Sep 25 '15 20:09

Kai Mou


People also ask

Can JSONObject be null?

JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

How do I check if a JSON property is null?

To check null in JavaScript, use triple equals operator(===) or Object is() method. If you want to use Object.is() method then you two arguments. 1) Pass your variable value with a null value.

How check JSONObject is null or not in android?

Try with json. isNull( "field-name" ) . I would go further and say to NEVER use has(KEY_NAME), replacing those calls to ! isNull(KEY_NAME).

How do I check if a JSON Object is empty?

return Object.keys(obj).length === 0 ; This is typically the easiest way to determine if an object is empty.


1 Answers

I suppose you're running the unit test outside of Android and compiling against android.jar. This lib contains only class and interface signatures without any implementation.

Solution:

Either execute the unit test in Android context (not on PC) or when running on PC, you have to load the "real" JSON library into your test.

like image 152
hgoebl Avatar answered Sep 20 '22 01:09

hgoebl