在SpringMVC的单元测试中,首先要对当前环境进行引入,比如:
@WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {NoticeServiceConfig.class})
错误情况:在NoticeServiceConfig类中如下:
@ComponentScan({"com.xx.xx.notice"}) @EnableJpaRepositories( basePackages = {"com.xx.xx.common.repository"}) @ImportResource("classpath:datasource_mysql.xml")报错:Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xx.xx.notice.repository.WeixinSenderRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}究其原因是因为我的dao层接口实现了JpaRepository接口,如果在单元测试中,就必须要引入该dao层所在的package,通过@EnableJpaRepositories指定到相应的包就可以,重点在于使用该注解,不能与@ComponentScan扫描的包的路劲重合,否则会提示:Could not autowire. There is more than one bean of 'WeixinSenderRepository' type. Beans:weixinSenderRepository,weixinSenderRepository.