java – Spring的MockMvc用于单元测试或集成测试吗?

Spring有两个MockMvc设置:

>独立设置
> WebApplicationContext设置

一般来说,MockMvc用于什么样的测试?单位还是整合?或两者?

我正确地说,使用独立设置(在Spring的应用程序上下文之外运行)允许您编写单元测试,并且使用WebApplicationContext设置可以编写集成测试吗?

最佳答案
这两种形式实际上都是集成测试,因为您正在测试代码与Spring DispatcherServlet和支持基础结构的集成.不同之处在于幕后使用的支持基础架构的数量.

详细信息记录在Spring参考手册中.

> Server-Side Tests
> Setup Options
> Difference With End-to-End Integration Tests

值得注意的摘录:

The “webAppContextSetup” loads the actual Spring MVC configuration
resulting in a more complete integration test. Since the TestContext
framework caches the loaded Spring configuration, it helps to keep
tests running fast even as more tests get added. Furthermore, you can
inject mock services into controllers through Spring configuration, in
order to remain focused on testing the web layer.

The “standaloneSetup” on the other hand is a little closer to a unit
test. It tests one controller at a time, the controller can be
injected with mock dependencies manually, and it doesn’t involve
loading Spring configuration. Such tests are more focused in 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
“standaloneSetup” is also a very convenient way to write ad-hoc tests
to verify some behavior or to debug an issue.

Just like with integration vs unit testing, there is no right or wrong
answer. Using the “standaloneSetup” does imply the need for some
additional “webAppContextSetup” tests to verify the Spring MVC
configuration. Alternatively, you can decide to write all tests with
“webAppContextSetup” and always test against actual Spring MVC
configuration.

The options provided in Spring MVC Test are different stops on the
scale from classic unit to full integration tests. To be sure none of
the options in Spring MVC Test are classic unit tests but they are a
little closer to it. For example you can isolate the service layer
with mocks injected into controllers and then you’re testing the web
layer only through the DispatcherServlet and with actual Spring
configuration, just like you might test the database layer in
isolation of the layers above. Or you could be using the standalone
setup focusing on one controller at a time and manually providing the
configuration required to make it work.

如有疑问,我建议您在发布问题之前先阅读参考手册. 😉

问候,

Sam(Spring TestContext Framework的作者)

转载注明原文:java – Spring的MockMvc用于单元测试或集成测试吗? - 代码日志