Spring整合Junit的使用详解
我们在编写完Spring的代码后,往往需要测试代码的正确性,这个时候就需要用到单元测试了。我们这里使用的版本是junit4.
一个程序的入口是main方法,但是junit中不存在main方法,是因为junit内部的原理是它自己内部就有个main方法,运行扫描带@Test注解的方法,然后反射调用该方法,完成测试。
调用Spring框架的测试代码:
@Test
public void function(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
AccountDao accountDao1 = applicationContext.getBean("AccountDao", AccountDao.class);
accountDao1.findAll();
}
我们发现这只是查询,还有增删改方法没有测试,但是这几个测试都有重复代码块,我们应该把它们抽取出来
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
AccountDao accountDao1 = applicationContext.getBean("AccountDao", AccountDao.class);
我们可以在外面定义一个全局变量,用来存储accountDao的值,并且通过@Autowired注解实现注入对象,这样每个方法就都可以使用它了.
@Autowired private AccountDao accountDao;
但是这样运行之后会爆出空指针异常!!!
这是因为Junit默认是不认识Spring框架的,所以它内部没有IOC容器,这样就算你有@Autowired这个注解,它也不知道从哪里注入数据,所以就会有这个异常。
问题原因分析出来后,我们就想,能不能自己提供一个IOC容器呢,即
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
往往在现实开发中,软件开发和软件测试是两个职位,上述代码如果是开发编写的话,往往没什么问题。但测试人员可能会不懂Spring的代码,所以需要另外一种办法,好在Spring为我们提供了整合Junit的使用。
首先引入Spring-test的jar坐标
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.5.RELEASE</version> <scope>test</scope> </dependency>
Spring给我们提供了一个main方法,这个main方法支持Spring框架,我们用这个main替换Junit的main方法。
@RunWith(SpringJUnit4ClassRunner.class)
在类上加上这个注解,@Runwith代表要替换的运行器,后面在字节码参数
告诉Spring配置文件/配置类的位置
@ContextConfiguration(locations = "classpath:bean.xml")
使用Contextfiguration注解可以完成该功能,locations表示配置文件的位置,加上classpath表示类路径。
至此整合结束,测试方法直接使用既可,但是这里有个版本问题,如果你使用的是Spring5.0以上的话,你的Junit版本必须是4.12以上!!!
不然会曝出
java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
这个错误
改完版本就可以正常运行测试方法了。
栏 目:JAVA代码
下一篇:源码解析JDK 1.8 中的 Map.merge()
本文标题:Spring整合Junit的使用详解
本文地址:http://www.codeinn.net/misctech/129796.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




