Unit testing Spring MVC applications with JUnit 5
Spring is a reliable and popular framework for building web and enterprise Java applications. In this article, you’ll learn how to unit test each layer of a Spring MVC application, using built-in testing tools from JUnit 5 and Spring to mock each component’s dependencies. In addition to unit testing with MockMvc, Mockito, and Spring’s TestEntityManager , I’ll also briefly introduce slice testing using the @WebMvcTest and @DataJpaTest annotations, used to optimize unit tests on web controllers and databases. Also see: How to test your Java applications with JUnit 5 . Overview of testing Spring MVC applications Spring MVC applications are defined using three technology layers: Controllers accept web requests and return web responses. Services implement the application’s business logic. Repositories persist data to and from your back-end SQL or NoSQL database. When we unit test Spring MVC applications, we test each layer separately from the others. We create mock implementations, typically using Mockito , for each layer’s dependencies, then we simulate the logic we want to test. For example, a controller may call a service to retrieve a list of objects. When testing the controller, we create a mock service that either returns the list of objects, returns an empty list, or throws an exception. This test ensures the controller behaves correctly. We’ll use Spring MVC to build and test a simple web service that manages widgets. The structure of the web service is shown here: Steven…