Analysis of spring boot test class without bean injection

Time:2021-4-3

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 App.java

So we have to add a note to the test class


@RunWith(SpringRunner.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


org.springframework.beans.factory.UnsatisfiedDependencyException:
 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 'com.sb.LibrarySystem.mapper.UserMapper' 
 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:


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

}

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


@RunWith(SpringRunner.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.