5

I'm relatively new to Java and I'm asking to write test of JSON response server. I found JSONassert very useful but I didn't succeed to write the method getRESTData.

Anybody can help please?

@Test
public void testGetFriends() throws JSONException {
    JSONObject data =  getRESTData("/friends/367.json");
    String expected = "{friends:[{id:123,name:\"Corby Page\"}"
            + ",{id:456,name:\"Solomon Duskis\"}]}";
    JSONAssert.assertEquals(expected, data, false);
}
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
david david
  • 51
  • 1
  • 1
  • 2
  • Thanks for your question macias. I don't know how to convert the url requested into json. In my example how i can get the json "/friends/367.json" from the url. – david david Apr 15 '15 at 11:21

2 Answers2

4

You can get the data as String and pass it into JSONAssert.assertEquals. Converting to JSONObject isn't necessary.

To fetch data from an URL, you can use URL.getContent method:

final String data = new URL("...").getContent();
String expected = "{friends:[{id:123,name:\"Corby Page\"}"
        + ",{id:456,name:\"Solomon Duskis\"}]}";
JSONAssert.assertEquals(expected, data, false);
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
1

This can also be achieved with ModelAssert - https://github.com/webcompere/model-assert , which can take anything serializable to JSON as an input:

@Test
public void testGetFriends() throws JSONException {
    JSONObject data =  getRESTData("/friends/367.json");
    String expected = "{friends:[{id:123,name:\"Corby Page\"}"
            + ",{id:456,name:\"Solomon Duskis\"}]}";
    
    assertJson(data).isEqualTo(expected);
}

IIRC JSONObject is essentially a Map, so assertJson will convert it to the internal JsonNode format it uses for comparison.

Ashley Frieze
  • 4,993
  • 2
  • 29
  • 23