【问题标题】:Java JSON unit test pass with wrong valueJava JSON 单元测试通过错误值
【发布时间】:2020-01-07 12:36:49
【问题描述】:

我有以下功能:

public class NorthboundApiLogicTest {

  @Test
  public void testIfParametersValuesAreCorrect() {
    String body = "{\"exception\":\"world\",\"error\":\"Not Found\",\"message\":\"hello\""
        + ",\"timestamp\":\"2020-01-07T12:26:48.334386Z\",\"status\":\"404\"}";
    try {
      JSONAssert.assertEquals("{message:hello, exception:world, status:403, error:Not Found}", 
          body, false);
    } catch (Exception e) {
      System.err.println(e);
    }
    System.out.println(body);
  }
}

我用 Maven 运行这个测试,奇怪的是它成功通过了。

但是,它不应该,因为我断言 status=403 但值是 404。我究竟做错了什么?

【问题讨论】:

  • 请注意,抛出 JSONException 并且您处于捕获状态。

标签: java jsonunit


【解决方案1】:

它甚至在对结构执行断言之前就无法解析 JSON,而您只是通过您的catch 记录它。

catch (Exception e) {
      System.err.println(e);
}

您需要让该异常从方法中抛出,或者捕获它并使用适当的消息调用fail()

然后解决您的不可解析 JSON 的问题,当然!

【讨论】:

  • 奇怪,因为根据这个jsonlint.com我的JSON是有效的。
  • {message:hello, exception:world, status:403, error:Not Found} 不是有效的 json
猜你喜欢
  • 2015-04-25
  • 1970-01-01
  • 2021-12-24
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
  • 1970-01-01
相关资源
最近更新 更多