繁体   English   中英

如何将 JSONObject 单元测试格式化为不是 null?

[英]How to format a JSONObject Unit test to not be null?

当我在 sendCommand 方法上运行以下单元测试时,我得到一个 null 指针异常。 如何将我的 JSON Object 格式化为正确的单位

我的单元测试:

@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());
        }
    }

我的方法:

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());
        }
    }

我的错误信息:

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)

此错误消息发生在 sendCommand() 的 Switch 语句中。

reader.getJSONObject("payload")不是JSONObject - 它是String

您应该在创建测试 object 时添加它

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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