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).

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>deringo</groupId>
	<artifactId>testproject</artifactId>
	<version>1.0-SNAPSHOT</version>
	<name>testproject</name>
	<description></description>

	<properties>
		<maven.compiler.source>8</maven.compiler.source>
		<maven.compiler.target>8</maven.compiler.target>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	</properties>

	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<version>5.7.0</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest -->
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest</artifactId>
			<version>2.2</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/io.smallrye/smallrye-rest-client -->
		<dependency>
			<groupId>io.smallrye</groupId>
			<artifactId>smallrye-rest-client</artifactId>
			<version>1.2.2</version>
		</dependency>
	</dependencies>

</project>
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"))
				));
	}

}