Analysis of spring boot test class without bean injection


This article mainly introduces the spring boot test class does not bean injection problem analysis, the article through the example code is very detailed, for everyone’s study or work has a certain reference learning value, need friends can refer to

Other messy configuration will not pull, first on the project structure diagram

After configuring the parameters, I found that the bean was not injected correctly when accessing the database by Src / test / Java class test. It is worth noting that the startup class of this project is called

So we have to add a note to the test class

@SpringBootTest(classes = App.class) 

Note: springboot (classes)= App.class )Classes is followed by the startup class, do not copy online configuration, write some Application.class Class names like application are the same as those in some official packages, so it’s easy to introduce wrong packages.

At first, I found this problem. I went to the Internet to see how other people’s configuration files were written. I tried it for a day, but it didn’t work. Later, I calmed down and copied the error message into the text

 Error creating bean with name 'com.springboot.LibrarySystem.mapper.UserMapperTest':
 Unsatisfied dependency expressed through field 'userMapper'; 
 nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
 No qualifying bean of type '' 
 available: expected at least 1 bean which qualifies as autowire candidate. 
 Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Or start with this test class

Originally, my class was like this:

@SpringBootTest(classes = Application.class)
public class UserMapperTest {


After modification, it is the same as the class name of my startup class:

@SpringBootTest(classes = App.class)
public class UserMapperTest {

Perfect solution!

If Baidu finds that the problem of checking is getting deeper and deeper, and more and more deviates from the initial problem, it is likely that the direction is deviated. Rearrange it and start again

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.