I use external API, which returns list of sorted by date Objects with many (approx. 30) properties.

I wrote simple Rest API using Spring Boot with one endpoint /newest_obj_name which just return currently newest name of Object from that list and ignore everything else.

How can I sufficiently test that code while the value from external API is constantly changing, so I cannot simply use String expected as in a code below?

Generally speaking how to approach whole testing issue in that scenario?

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyTest {

    @LocalServerPort
    private int port;

    private TestRestTemplate restTemplate = new TestRestTemplate();

    private HttpHeaders headers = new HttpHeaders();

    @Test
    public void testRetrieveNewest() {

        HttpEntity<String> entity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> response = restTemplate.exchange(
                createURLWithPort("/newest_obj_name"),
                HttpMethod.GET, entity, String.class);

        String expected = "{\"name\":\"crazy\"}";

        try {
            JSONAssert.assertEquals(expected, response.getBody(), false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private String createURLWithPort(String uri) {
        return "http://localhost:" + port + uri;
    }
}

0 Answers