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:
Then, add a new JUnit class under test/java
to test our end points. Let's call it RESTAPITest.java
with the following content:
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.