首页 > 解决方案 > @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.这是否意味着它仍然加载应用程序上下文?或者,也许我没有正确理解它。

标签: spring-bootspring-test

解决方案


@WebMvcTest您仍然可以获得应用程序上下文,但不是完整的应用程序上下文。

启动的 Spring Test Context 仅包含与测试 Spring MVC 组件相关的 bean:@Controller@ControllerAdviceConverterFilterWebMvcConfigurer

注入MockMvcusing@Autowired MockMvc mockMvc;还表明您正在使用 Spring 上下文,并且 JUnit Jupiter 扩展(@ExtendWith(SpringExtension.class它是 的一部分@WebMvcTest)通过从 Test 上下文中检索它们来处理您的字段。

如果您仍然不希望启动 Spring Test 上下文,则可以仅使用 JUnit 和 Mockito 编写单元测试。通过这样的测试,您将只能验证控制器的业务逻辑,而不能验证以下内容:正确的 HTTP 响应、路径变量和查询参数解析、不同 HTTP 状态的异常处理等。

您可以在此处阅读有关不同Spring Boot 测试切片的更多信息以及如何使用MockMvc来测试您的 Web 层


推荐阅读