spring @webMvcTest未排除和加载标记为@Repository的bean

您所在的位置:网站首页 mockbean注解 spring @webMvcTest未排除和加载标记为@Repository的bean

spring @webMvcTest未排除和加载标记为@Repository的bean

#spring @webMvcTest未排除和加载标记为@Repository的bean | 来源: 网络整理| 查看: 265

我有一个@RestController,它在@Autowire字段中只有一个依赖项,该依赖项是@component,该组件的类定义有一些自动连接的字段,这些字段是@service,这些服务有一些@ repository。在整个流程中,我使用了Kafka、Quartz、Cassandra和DB2。因此,当我为控制器创建单元测试用例时,我不想设置整个应用程序。因此,我决定使用@webMvcTest,并在控制器类的唯一依赖项上使用@MockBean。但是我的测试抛出了异常,因为它试图创建一个标记为@repository的Dao bean。

@ActiveProfiles("test") @WebMvcTest(controllers = MyControllerTest .class) class MyControllerTest { @MockBean MyControllerDependency dependency; @Autowired MockMvc mockMvc; @Test void test_something() throws Exception { assert(true); } }

下面是代码的简化版本

@Component class MyControllerDependency { @AutoiWired MyCustomService service; } @Service class MyCustomService{ @Autowired MyCustomDao dao; } @Repository class MyCustomDao{ @Autowired private JdbcTemplate template; }

我在测试中得到以下异常。

Exception *************************** APPLICATION FAILED TO START *************************** Description: Field template in com.....MyCustomDao` required a bean of type 'org.springframework.jdbc.core.JdbcTemplate' that could not be found.

问题是,当我使用@WebMvcTest slice并且已经模拟了唯一需要的依赖项MyControllerDependency时,为什么spring test context试图加载MyCustomDao,它被注解为@Repository。我可以用SpringbootTest和AutoconfigureMockMVC进行集成测试,但是为了编写控制器的Junit测试,我需要使用WebMvcTest slice。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3