在@WebMvcTest中指定@SpringBootApplication

时间:2019-04-08 15:51:13

标签: spring spring-boot spring-mvc spring-boot-test

使用@WebMvcTest将通过查找@SpringBootConfiguration类(例如@SpringBootApplication)来自动配置所有Web层bean。

如果配置类位于其他程序包中,并且无法通过扫描找到,我可以直接将其提供给@WebMvcTest吗?

2 个答案:

答案 0 :(得分:0)

以下内容将指向正确的@SpringBootApplication类:

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(controllers = {MyController.class})
@ContextConfiguration(classes={MySpringBootApplicationClass.class})
public class MyControllerTest {
    //...
}

答案 1 :(得分:0)

如果您使用 @WebMvcTest 进行测试,则意味着您主要专注于测试spring mvc层,而不会更深入地研究应用程序。

  

因此,仅当测试 将重点放在Spring上时,才能使用此注释   MVC组件默认情况下,使用@WebMvcTest注释的测试将   还可以自动配置Spring Security和MockMvc(包括对   HtmlUnit WebClient和Selenium WebDriver)。为了更细粒度   可以通过@AutoConfigureMockMvc注释控制MockMVC   通常将 @WebMvcTest 与    @MockBean @Import 创建您的 @Controller bean所需的任何协作者

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({ CustomerConfig.class, SchedulerConfig.class })
public class AppConfig {

}

然后您可以使用@import带注释的测试类中的@WebMvcTest导入此配置类,并且应该在春季之前将bean拿起。

参考:https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTest.html

相关问题