学习笔录-SPRING BOOT

【已解决】springboot在使用redisTemplate的测试的时候报空指针

在使用springboot项目中,使用RedisTemplate在Junit测试的时候,报RedisTemplate空指针:来看看修改前:修改后:在类上加入:@RunWith(SpringRunner.class)这个注解。

SpringBoot在JUnit测试中使用RedisTemplate报空指针,是因为单纯的测试类没有启动Spring容器,RedisTemplate无法注入而是null。解决方法:在测试类上添加@RunWith(SpringRunner.class)注解,让JUnit以Spring容器环境运行测试,之后即可正常注入RedisTemplate并操作Redis。

  • 报空指针的根源是测试类未启动Spring容器,注入对象为null
  • 解决方法:在测试类上添加@RunWith(SpringRunner.class)注解
  • SpringRunner让JUnit测试运行在Spring测试环境中

在使用springboot项目中,使用RedisTemplate在Junit测试的时候,

原创不易,完成人机校验,阅读全文

常见问题

测试类使用RedisTemplate为什么报空指针?

普通JUnit测试不会启动Spring容器,RedisTemplate没有被注入为null。在测试类上添加@RunWith(SpringRunner.class)注解启动容器即可解决。

相关推荐