简体   繁体   中英

How to format a JSONObject Unit test to not be null?

When I run the following unit test on the sendCommand Method, I get a null pointer exception. How do I format my JSON Object to properly Unit

My Unit test:

@Test(expected = IllegalStateException.class)
    public void shouldThrowIllegalStateExceptionOnUnknownCommand() {
        try {
            JSONObject test = new JSONObject();
            test.put("name", "UnitTest");
            test.put("payload", "{ \"example\": \"payload\" }");
            testClassObject.sendCommand(test);
        } catch (JSONException e) {
            Log.e(TAG, "failed to parse JSON Object Unit test" + e.getMessage());
        }
    }

My Method:

public void sendCommand(JSONObject reader) {
        try {
            String commandName = reader.getString("name");
            JSONObject data = reader.getJSONObject("payload");
            switch (commandName)
            {
                case "ValidCommand":
                    //Do Stuff
                    break;
                default:
                    Log.i(TAG, "Unknown command");
                    throw new IllegalStateException("Unknown command: " + commandName);
            }
        } catch (JSONException e) {
            Log.e(TAG, " Failed to parse JSON Object / array " + e.getMessage());
        }
    }

My Error message:

Unexpected exception, expected<java.lang.IllegalStateException> but was<java.lang.NullPointerException>
    java.lang.Exception: Unexpected exception, expected<java.lang.IllegalStateException> but was<java.lang.NullPointerException>
        at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)

This error message is occurring at the Switch statement of sendCommand().

reader.getJSONObject("payload") isn't a JSONObject - it's a String

you should add this when you create you test object

test.put("payload", new JSONObject("{ \"example\": \"payload\" }"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM