@WebMvcTest 加载应用上下文

@ WebMvcTest loading application context

我有一个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":..........

As per spring doc we can narrow the tests to only the web layer by using @WebMvcTest. 这是否意味着它仍然加载应用程序上下文?也可能是我没有理解正确。

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

启动的 Spring 测试上下文仅包含与测试您的 Spring MVC 组件相关的 bean:@Controller@ControllerAdviceConverterFilter, WebMvcConfigurer.

使用 @Autowired MockMvc mockMvc; 注入 MockMvc 还表明您正在使用 Spring 上下文和 JUnit Jupiter 扩展(@ExtendWith(SpringExtension.class,它是 @WebMvcTest) 负责通过从测试上下文中检索它们来解析您的字段。

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

您可以阅读更多关于不同 Spring Boot Test slices here and on how to use MockMvc to test your web layer 的内容。