Spring boot test测试中@Autowired不起作用 报空指针异常
测试代码如下:
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;
public class MoveSysUserTest {
@Autowired
private MoveSysUser moveSysUser;
@Test
public void testMoveSysUser() {
boolean res = moveSysUser.moveSysUser();
System.out.println(res);
}
此时运行,会提示moveSysUser为空,报空指针异常
解决方法:
1、添加注解
@RunWith(SpringRunner.class) @SpringBootTest
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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MoveSysUserTest {
@Autowired
private MoveSysUser moveSysUser;
@Test
public void testMoveSysUser() {
boolean res = moveSysUser.moveSysUser();
System.out.println(res);
}
}
注:如果@RunWith 飘红则需要在pom文件添加junit依赖并且把Test注解使用junit
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
<version>4.12</version>
</dependency>
2、继承一个带有这个注解的类

浙公网安备 33010602011771号