Unit Testing REST API with Spring Boot

In the last chapter, we looked at how Spring Boot makes it easy to develop REST APIs. We understood the basic features of Spring Boot by creating a couple of simple Hello World REST APIs. We created REST APIs for GET, POST, PUT, and DELETE operations for the Todo REST API.

In this chapter, let's focus on writing great unit and integration tests for the REST API when it is developed with Spring Boot.

Unit testing focuses on writing automated tests for the responsibilities of each method or a group of methods. Unit testing acts as a safety net against future defects. It helps to catch defects earlier.

In unit tests for REST APIs, we launch REST API controllers in isolation and then test them. We use the Spring Mock Model, View and Controller (MVC) framework to launch Spring contexts with only the web layer components, and we mock out all other dependencies.

Integration tests help us to test multiple layers of an application in combination. In integration tests, we launch the entire Spring context, including business and data components. We invoke the REST API, and assert the responses.

This chapter answers the following questions:

  • How do you write unit tests for different REST API methods that have been implemented with Spring MVC?
  • How can you launch Spring contexts for unit tests just for the web layer components, and using the Spring Mock MVC framework?
  • How do you write integration tests for different REST API methods that have been implemented with Spring MVC?
  • Why is Spring Boot Starter Test a great place to start when writing unit and integration tests?
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset