junit 如何将JSONObject单元测试格式化为非空?

p1iqtdky  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(115)

当我在sendCommand方法上运行下面的单元测试时,我得到了一个空指针异常。
我的单元测试:

@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语句中。

uwopmtnx

uwopmtnx1#

reader.getJSONObject("payload")不是JSONObject-它是String
您应该在创建测试对象时添加该属性

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

相关问题