问题描述
应公司要求使用低版本Springboot(2.0.1.RELEASE),启动测试类SpringBootTest时无法依赖注入,使用@Autowired注解会报红,一旦强行运行测试类,就会报空指针(java.lang.NullPointerException)异常:
原因分析
猜测是SpringBoot版本问题,因为在高版本上不用这么麻烦,直接用@SpringBootTest一个注解即可搞定。
解决方案
1、首先检查你的测试类路径有没有写对
2、在测试类上添加注解:
@SpringBootTest(classes=ApiApplication.class)
@RunWith(SpringRunner.class)
第一行,classes就填写你SpringBoot主启动类的Class;
第二行,@RunWith(SpringRunner.class)
写死。引入的包是:import org.junit.runner.RunWith;
完整代码如下:
package cn.xxwlh.api;
import cn.xxwlh.api.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes=ApiApplication.class)
@RunWith(SpringRunner.class)
public class ApiApplicationTest {
@Autowired
private UserService userService;
@Test
public void Test(){
userService.test();
}
}
问题解决。
补充:SpringBoot多模块项目使用测试类
如果一个项目目录是多模块的(父工程包含了子工程),如下图:
你的SpringBoot主启动类在某一个工程里。那么就不能用上面的路径建测试类了。要把测试类的根目录(Test Sources Root)建在主启动类所在工程的如下图位置:
该类的代码同上。这样就可以在多模块项目中使用测试类了。