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.