測試代碼如下:
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、繼承一個帶有這個注解的類