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、继承一个带有这个注解的类

 

posted @ 2020-12-15 17:50  浅笑19  阅读(2731)  评论(0编辑  收藏  举报