Testing endpoints with OkHttp

info

API testing is a type of software testing that involves testing application programming interfaces (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 utilizing a lightweight http client library such as OkHttp for functional testing (in the form of unit tests), but use Postman for the other types of testings (e.g. reliability, performance etc.).

Functional testing with OkHttp

Add the following dependency to your build.gradle file:

implementation 'com.squareup.okhttp3:okhttp:4.9.0'

Then, add a new JUnit class under test/java to test our end points. Let's call it RESTAPITest.java with the following content:

import okhttp3.*;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.sql.*;
import static org.junit.Assert.*;
public class RESTAPITest {
static OkHttpClient client;
@BeforeClass
public static void beforeClassTests() throws SQLException {
client = new OkHttpClient();
}
@Test
public void testListAuthors() throws IOException {
Request request = new Request.Builder()
.url("http://localhost:7000/authors")
.build();
Response response = client.newCall(request).execute();
assertEquals(200, response.code());
}
@Test
public void testAddAuthor() throws IOException {
RequestBody formBody = new FormBody.Builder()
.add("name", "Ernest Hemingway")
.add("numOfBooks", "25")
.add("nationality", "American")
.build();
Request request = new Request.Builder()
.url("http://localhost:7000/addauthor")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
assertEquals(201, response.code());
}
}

First, we need to make sure we instantiate a client from OkHttpClient class. We need to do this only once, before any tests are executed. Then we can compose requests and send them through via the instantiated client. Currently, we have two tests. The first one tests the authors API end point and the second one creates a new author in the Authors table by sending a post request to the addauthor route.

tip

Currently, we only rely on the returned status code to gain confidence the end points are working as expected. Ideally, you would want to add appropriate assertions on the returned content as well.

info

Refer to OkHttp website for various examples and detailed documentations.