Unit test reports an error nosuchbeandefinitionexception

Question

During the development of springboot project, unit tests are used to run a service. It is found that a bean called cannot be found, and the error is:

  org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.gaosiedu.gsl.mq.base.MqSendService’ available: expected at least 1 bean which qualifies as autowire candidate.

Can’t find a qualified bean

However, I clearly defined this bean, but not in the way of annotation, but in the way of XML

In the main class of the springboot project, an annotation is added   @ importresource , add the bean definition in the corresponding configuration file, as follows:

 @ ImportResource({
  ”classpath:*dubbo-*-spring.xml”,
  ”classpath:*mq-*-spring.xml”
})

 

Settle

Finally, it is found that the reason is that the classpath specified in the @ importresource annotation does not refer to the same place when it is officially run in the server and when it is unit tested

During the formal operation of the server, it needs to be in the folder with the folder type of [sources root]
during unit test, it needs to be in the folder with the folder type of [test sources root]

How to set the folder type?Just right click the folder and select [mark directory as], as shown in the figure:

  

Under normal circumstances, main/resources is the [sources root] type, and test/resources is the [test sources root] test type
I only created a new configuration file under main/resources, so I will report an error. When the corresponding two configuration files are copied to the test/resources directory, there is no problem

PS: a new configuration file should be created in the test directory only if the classpath: configuration file is clearly specified. This is not necessary for general configuration files, such as configuration database connection files

 

Original article, welcome to reprint, reprint please indicate the source

Similar Posts: