This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Framework 6.2.0!spring-doc.cn

Setup Options

MockMvc can be set up in one of two ways.spring-doc.cn

WebApplicationContext

Point to Spring configuration with Spring MVC and controller infrastructure in it.spring-doc.cn

Standalone

Point directly to the controllers you want to test and programmatically configure Spring MVC infrastructure.spring-doc.cn

Which setup option should you use?spring-doc.cn

A WebApplicationContext-based test loads your actual Spring MVC configuration, resulting in a more complete integration test. Since the TestContext framework caches the loaded Spring configuration, it helps keep tests running fast, even as you introduce more tests in your test suite using the same configuration. Furthermore, you can override services used by your controller using @MockitoBean or @TestBean to remain focused on testing the web layer.spring-doc.cn

A standalone test, on the other hand, is a little closer to a unit test. It tests one controller at a time. You can manually inject the controller with mock dependencies, and it does not involve loading Spring configuration. Such tests are more focused on style and make it easier to see which controller is being tested, whether any specific Spring MVC configuration is required to work, and so on. The standalone setup is also a very convenient way to write ad-hoc tests to verify specific behavior or to debug an issue.spring-doc.cn

As with most "integration versus unit testing" debates, there is no right or wrong answer. However, using standalone tests does imply the need for additional integration tests to verify your Spring MVC configuration. Alternatively, you can write all your tests with a WebApplicationContext, so that they always test against your actual Spring MVC configuration.spring-doc.cn