Setup Options
有两种方式可以设置 MockMvc。一是直接指向你想要测试的 controller 并对 Spring MVC 基础架构进行编程配置。另一种方法是使用其中包含 Spring MVC 和 controller 基础架构的 Spring 配置进行设置。
MockMvc can be setup in one of two ways. One is to point directly to the controllers you want to test and programmatically configure Spring MVC infrastructure. The second is to point to Spring configuration with Spring MVC and controller infrastructure in it.
你应该使用哪种设置选项?
Which setup option should you use?
使用 ApplicationContext
加载你的实际 Spring MVC 配置,导致基于 WebApplicationContext
的测试加载你的实际 Spring MVC 配置,从而生成更完整的集成测试。由于 TestContext 框架缓存了加载的 Spring 配置,因此它有助于保持快速运行的测试,即使你在测试套件中使用相同的配置引入更多测试。此外,你可以使用 @MockitoBean
覆盖控制器使用的服务,以便专注于测试 Web 层。
The use of an ApplicationContext
loads your actual Spring MVC configuration, resulting
The 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
to remain focused on
testing the web layer.
另一方面,独立测试更接近单元测试。它每次测试一个控制器。你可以手动注入带有模拟依赖项的控制器,并且不涉及加载 Spring 配置。此类测试更注重样式,让你更容易看到正在测试哪个控制器,工作时是否需要任何特定的 Spring MVC 配置,等等。独立设置也是编写临时测试以验证特定行为或调试问题的一种非常便捷的方法。
The 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 MVC 配置。或者,您可以使用 WebApplicationContext
编写所有测试,以便始终根据实际 Spring MVC 配置进行测试。
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.