SpringBoot测试类注入Bean失败的原因及分析
目录
- 2.2版本之后
- 导包pom.XML
- 注解
- 测试
- 2.2版本之前
- 导包pom.xml
- 注解
- 测试
- 注意包路径需要一致
- 总结
针对SpringBoot的测试类,2.2版本之前和之后是不一样的。
2.2版本之后
导包pom.xml
添加test依赖
<!-- starter-test:junit + spring-test + mockito -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
注解
- @SpringBootTest—import org.springframework.boot.test.context.SpringBojso编程客栈tTest;
- @Tesjst—import org.junit.jupiter.api.Test;
测试
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @author wangkanglu
* @versjavascription 1.0
* @description
* @date 2024-07-07 11:32
*/
@SpringBootTest
public class TestMain {
@Test
public void test1(){
System.out.println("-----");
}
}
2.2版本之前
导包pom.xml
添加test依赖
<!-- starter-test:junit + spring-test + mockito -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
注解
- @SpringBootTest—import org.springframework.boot.test.context.SpringBootTest;
- @RunWith(SpringRunner.class)—import org.junit.runner.RunWith;
- @Test—import org.junit.Test;
测试
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @author wangkanglu
* @version 1.0
* @description
* @date 2024-07-07 11:32
*/
@SprijavascriptngBootTest
@RunWith(SpringRunner.class)
public class TestMain {
@Test
public void test1(){
System.out.println("-----");
}
}
注意包路径需要一致
注意测试类的包名和启动类的包名一定要一致,否则扫描不到bean对象会报空异常,如下图:

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
加载中,请稍侯......
精彩评论