Java JSON unit test pass with wrong value

312 Views Asked by At

I have the following function:

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

I run this test with Maven, and strangely it pass successfully.

enter image description here

However, it should not, because I assert that status=403 but the value is 404. What am I doing wrong?

1

There are 1 best solutions below

2
Brian Agnew On BEST ANSWER

It's failing to parse the JSON before it even performs an assertion on the structure, and you're simply logging that via your catch.

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

You need to let that exception be thrown from the method, or catch it and call fail() with an appropriate message.

And then fix the issue of your non-parseable JSON, of course!