JUnit测试@DataJpaTest与@ComponentScan冲突

今天在写JUnit测试的时候,发现一个bug,首先将测试代码贴出来:

@DataJpaTest
@RunWith(SpringRunner.class)
//@ContextConfiguration(classes= RepositoryTest.class)
public class SubscriptionRepositoryTest{
}

SpringBoot的启动类如下:

@SpringBootApplication
@EnableJpaRepositories
@ComponentScan("io.majing")
@EnableAsync
public class UserCenterApp{
}

执行的时候报了一个错误:

Error creating bean with name 'userCreditPublisher' defined in file 
[C:\devnote\backend\devnote\user-center\target\classes\io\majing\usercenter\message\UserCreditPublisher.class]: 
Unsatisfied dependency expressed through constructor parameter 0; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.amqp.core.AmqpTemplate' available: 
expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

在这样的情况下,如果将启动类中的注解@ComponentScan("io.majing")注释掉;然后测试正常通过;

问题分析:

我们知道,@DataJpaTest这个注解只会初始化@Repository注解的类,但是为什么在添加了@ComponentScan后,SpringBoot会初始化@Service;而去掉注解之后就不会初始化@Service呢;通过网上查询后知道,@DataJpaTest@ComponentScan有冲突;因此对应有两种方案:

1、去掉启动类的注解@ComponentScan

2、重新增加一个启动类

@SpringBootConfiguration
@EnableAutoConfiguration
public class RepositoryTest {
    public static void main(String[] args) {
        SpringApplication.run(RepositoryTest.class, args);
    }
}

并且在测试类中将启动类修改成新增加的这个类:

@ContextConfiguration(classes= RepositoryTest.class)
public class SubscriptionRepositoryTest {
}

好了,测试通过;

版权声明:著作权归作者所有。

不错不错,springboot启动的时候如果有@ComponentScan会加载了额外的类,而不是像@DataJpaTest注解只记载@Repository;说得很清楚
感谢,按照您的说法,解决了我的问题。原理也说得很清楚
thumb_up 1 | star_outline 1 | textsms 2