SSM框架单元测试出现NullPointerException错误

背景:我这边使用SSM框架已经写好了sql和Mapper接口,现在想要通过单元测试进行验证,但是发现使用test单元测试报NullPointerException

在这里插入图片描述

解决方法:

  • 在测试类上添加如下代码:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")

这里可能会出现不识别@RunWith,@ContextConfiguration的情况。这是因为没有对应的包依赖。添加下面的包

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>5.2.9.RELEASE</version>
</dependency>

这里注意:spring-test的版本要和spring-context的版本一致

  • 如果还是出错那可能就是junit的版本过低导致,要提高其版本(我这错误提示是要求4.12版本以上)
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.13</version>
  <scope>test</scope>
</dependency>

之后在测试就可以了

出错原因:

@RunWith(SpringJUnit4ClassRunner.class)作用是让测试运行于Spring测试环境

@ContextConfiguration注解表示,在整合JUnit4测试时,使用注解引入多个配置文件

通过上面两个注解我们就可以使用Spring的测试环境了,由Spring来帮助我管理bean,如果没有上面的注解,那我们就只能通过自己管理bean.

既然我们知道了原因,那我们就应该明白了,除了这一种方式可以解决问题,还有另外一种方式:在核心配置文件中配置bean,然后自己进行管理和获取

@Test
  public void test(){
      ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
      UserService userService = (UserService) context.getBean("userServiceImpl");
      List<User> users = userService.allUsers();
      users.forEach(System.out::println);
  }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值