"@AutoConfigureWebMvc"和"@AutoConfigureMockMvc"之间的区别是什么?

43

我应该在什么情况下使用它们各自?


1个回答

50

@AutoConfigureWebMvc

如果您需要为测试配置 Web 层,但不需要使用 MockMvc,请使用此选项。

它启用与 Web 层相关的所有自动配置,且仅限于Web层。这是整体自动配置的子集。

它包括以下自动配置(请参见spring.factories

# AutoConfigureWebMvc auto-configuration imports
org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc=\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration

@AutoConfigureMockMvc

使用此注解仅配置MockMvc

启用与MockMvc相关的全部自动配置,仅限于MockMvc。这是总体自动配置的子集。

它包括以下自动配置(请参见spring.factories

# AutoConfigureMockMvc auto-configuration imports
org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc=\
org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration,\
org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityAutoConfiguration,\
org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration,\
org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration

@WebMvcTest

包含了@AutoConfigureWebMvc@AutoConfigureMockMvc,还有其他功能。


非常感谢您提供如此清晰的解释。您为我节省了很多麻烦。 - dvogel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接