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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM