Testing API

API testing is a type of software testing that involves testing APIs directly and as part of integration testing to determine if they meet expectations for functionality, reliability, performance, and security. When it comes to testing API endpoints, you can do this manually or automatically. Postman offers functionalities for both. There are also Java libraries that assist you with API testing. I personally prefer to use both manual and automated testing.

For manual testing, we will build a collection of HTTP requests in Postman, targeting our API. In Module-1, I've shown you how to create a Postman collection (see here). I've created a collection called course-search-api in Postman. Here is the Get request from previous section, saved into the collection. (Notice I'm using a variable to encode the API base url.)

For automatic testing, we will write unit tests using the HTTP client library Unirest. Add the following to the dependencies clause of build.gradle:

testImplementation 'com.konghq:unirest-java:3.11.09'

Open the Gradle tool window and refresh the Gradle project. Next, add the following suit of tests to your project:

import com.google.gson.Gson;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;

import java.net.URISyntaxException;

class ApiServerTest {

  private final static String BASE_URL = "http://localhost:4567";
  private static final Gson gson = new Gson();

  @BeforeAll
  static void runApiServer() throws URISyntaxException {
    ApiServer.main(null); // run the server
  }

  @AfterAll
  static void stopApiServer() {
    ApiServer.stop();
  }

}

Notice the runApiServer() and stopApiServer() methods. The idea is that we start up the (local) server before running any of the tests, and then stop it after all the tests has been executed. The ApiServer.stop() method is not implemented yet. Add it to the ApiServer class:

/**
 * Stop the server.
 */
public static void stop() {
  Spark.stop();
}

Let's add a simple test:

@Test
public void getCoursesWorks() throws UnirestException {
  final String URL = BASE_URL + "/api/courses";
  HttpResponse<JsonNode> jsonResponse = Unirest.get(URL).asJson();
  assertEquals(200, jsonResponse.getStatus());
  assertNotEquals(0, jsonResponse.getBody().getArray().length());
}

Run the test and make sure it passes.