spring-boot - @WebMvcTest 加载应用上下文
问题描述
我有一个GreetingController
@Controller
public class GreetingController {
@RequestMapping("/greeting")
public @ResponseBody String greeting() {
return "Hello, same to you";
}
}
和GreetingControllerTest
@WebMvcTest(GreetingController.class)
public class WebMockTest {
@Autowired
private MockMvc mockMvc;
@Test
public void greetingShouldReturnMessageFromService() throws Exception {
this.mockMvc.perform(get("/greeting")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello, same to you")));
}
}
我在 intelliJ 中运行测试,希望它不会加载应用程序上下文,但它从启动应用程序开始。
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.5.RELEASE)
{"thread":"main","level":"INFO","loggerName":..........
根据spring doc we can narrow the tests to only the web layer by using @WebMvcTest.
这是否意味着它仍然加载应用程序上下文?或者,也许我没有正确理解它。
解决方案
@WebMvcTest
您仍然可以获得应用程序上下文,但不是完整的应用程序上下文。
启动的 Spring Test Context 仅包含与测试 Spring MVC 组件相关的 bean:@Controller
、@ControllerAdvice
、Converter
、Filter
、WebMvcConfigurer
。
注入MockMvc
using@Autowired MockMvc mockMvc;
还表明您正在使用 Spring 上下文,并且 JUnit Jupiter 扩展(@ExtendWith(SpringExtension.class
它是 的一部分@WebMvcTest
)通过从 Test 上下文中检索它们来处理您的字段。
如果您仍然不希望启动 Spring Test 上下文,则可以仅使用 JUnit 和 Mockito 编写单元测试。通过这样的测试,您将只能验证控制器的业务逻辑,而不能验证以下内容:正确的 HTTP 响应、路径变量和查询参数解析、不同 HTTP 状态的异常处理等。
您可以在此处阅读有关不同Spring Boot 测试切片的更多信息以及如何使用MockMvc
来测试您的 Web 层。
推荐阅读
- odbc - 在 c# 中使用 odbc 连接到雪花
- wix - ICE03:无效的语言 ID。不抑制文件信息检索的解决方案
- c# - 根据日期从 Sqlite 数据库中调出数据
- ios - facebook登录错误,react-native ios expo
- c++ - 在构造函数代码之前禁用默认类成员初始化
- r - 在ggplot2中将误差条与每组不同数量的条对齐
- python - 使用条件和排名进行分组的 Python/Pandas 实现
- c# - 如何创建 IOptions
来自 T 的自定义实例(不是通过 DI) - ios - 为自定义视图调用 NSBundle(使用 loadNibName)后访问 IBOutlets 的最佳方法
- amazon-s3 - 我可以使用 AWS S3 + Cloudflare 为我的移动应用程序托管静态 JSON 文件吗?