【问题标题】:@ WebMvcTest loading application context@WebMvcTest 加载应用程序上下文
【发布时间】:2021-03-01 11:33:40
【问题描述】:

我有一个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-boot spring-test


【解决方案1】:

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

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

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

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

您可以阅读更多关于不同的Spring Boot Test slices here 以及如何use MockMvc to test your web layer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 2021-02-19
    • 2016-07-06
    • 2012-10-04
    • 1970-01-01
    • 2021-07-27
    • 2018-12-25
    相关资源
    最近更新 更多