Categories
Java

Test driven Json Analysis

To analyse an unknown Json API I setup a small project with Smallrye Rest Client to access the Json structure. I added JUnit for a test driven approach and Hamcrest for Matchers (like assertThat or is).



    4.0.0
    deringo
    testproject
    1.0-SNAPSHOT
    testproject
    

    
        8
        8
        UTF-8
        UTF-8
    

    
        
        
            org.junit.jupiter
            junit-jupiter-api
            5.7.0
            test
        
        
        
            org.hamcrest
            hamcrest
            2.2
            test
        
        
        
            io.smallrye
            smallrye-rest-client
            1.2.2
        
    

package deringo.testproject;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.junit.jupiter.api.Test;

public class TestJson {

    @Test
    public void testClientBuilderWorking() {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target("https://www.intensivregister.de/api/public/intensivregister");
        Response response = target.request(MediaType.APPLICATION_JSON).get();
        assertThat(response.getStatus(), is(200));
        JsonObject jo = response.readEntity(JsonObject.class);
        int rowCount = jo.getJsonNumber("rowCount").intValue();
        JsonArray ja = jo.getJsonArray("data");
        assertThat(ja.size(), is(rowCount));
        assertNotNull(ja.get(0).asJsonObject().getJsonObject("krankenhausStandort").getString("id"));

        ja.forEach(value -> 
                assertThat(
                        value.asJsonObject().getString("id"),
                        is(value.asJsonObject().getJsonObject("krankenhausStandort").getString("id"))
                ));
    }

}