当我们测试jdbc是否连接成功,出现空指针异常,这时不要慌张,首先检查是否引入依赖,依赖的格式是否正确。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
如果这个没有问题,我们需要查看注解添加的是否正确,springboot使用 test,需要添加两个注解@RunWith和@SpringBootTest。而@RunWith需要引用SpringRunner类。
如下:
@SpringBootTest
@RunWith(SpringRunner.class)
class ForumApplicationTests {
@Resource
private UserMapper userMapper;
@Resource
private DataSource dataSource;
@Test
void contextLoads() {
System.out.println("论坛系统");
}
@Test
void testConnection(){
System.out.println("dataSource = " + dataSource.getClass());
}
@Test
void testMybatis(){
User user = userMapper.selectByPrimaryKey(1l);
System.out.println(user);
}
}
我在遇到空指针异常就是因为没有添加@RunWith(SpringRunner.class),它作用表明Test测试类要使用注入的类,比如@Autowired注入的类,有了@RunWith(SpringRunner.class)这些类才能实例化到spring容器中,自动注入才能生效。