7

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();
        }
3
  • Can you post code for a minimal program that can be run? I dropped the above into a Java class and ran it successfully. (My only modification was changing assertEquals to Assert.assertEquals.) Commented Sep 25, 2015 at 20:30
  • Just added it. Thanks Commented Sep 26, 2015 at 2:27
  • The answer for your question is here: stackoverflow.com/a/35675861/3032209 Commented Feb 27, 2016 at 21:50

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

How do I load the "real" JSON library into a test?
What do you use? Gradle, Maven, ...? In Gradle and Maven you can define a compile/test dependency to org.json.
Thanks. I use gradle and after adding "testCompile 'org.json:json:20140107'" to build.gradle I can now use JSONObjects in tests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.