问题
SpringBoot单元测试,无法识别注入的Service属性,报错service is null
java.lang.NullPointerException: Cannot invoke "com.feng.mybatisplusdemo.service.IUserService.save(Object)" because "this.userService" is null
分析
- @Autowired 注解不起作用:测试类上是否有@RunWith(SpringRunner.class) 和@SpringBootTest 注解,没有 @Autowired 注解就不会生效。
- Service类的命名不正确:确保你的 Service 类的命名符合规范,以及在测试类中正确地注入了 Service 类的实例。
- Test类的扫描路径不对:默认情况下,SpringBoot 在扫描测试类时会默认扫描与主类相同包路径的类。如果 Service类放在了其他包路径下,那么需要在测试类中指定此路径。
解决
加入注解
@SpringBootTest

最低0.47元/天 解锁文章
891






