一、加入依赖包
1.使用spring4的测试框架需要加入以下依赖包:
JUnit 4
spring-Test (Spring框架中的test包)
spring-aop(Spring框架中的AOP包,spring4整合junit测试需要依赖aop的包了)
使用maven,在基于spring的项目中添加如下依赖:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
二、创建测试类
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) // 使用junit4进行测试
@ContextConfiguration(locations = "classpath:applicationContext.xml")//加载配置文件
public class Test1 {
}
解释所用到的注解
@RunWith 用于指定junit运行环境,是junit提供给其他框架测试环境接口扩展,为了便于使用spring的依赖注spring提供了org.springframework.test.context.junit4.SpringJUnit4ClassRunner作为Junit测试环境
1
@ContextConfiguration导入配置文件
如果只有一个配置文件
@ContextConfiguration(locations = "classpath:applicationContext.xml")
1
如果有多个配置文件
@ContextConfiguration(locations = { "classpath:/applicationContext1.xml", "classpath:/applicationContext2.xml" })
1
创建自己的测试类
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.huafeng.servicetest.Car;
@RunWith(SpringJUnit4ClassRunner.class) // 使用junit4进行测试
@ContextConfiguration(locations = "classpath:applicationContext.xml")//加载配置文件
public class Test1 {
@Autowired//spring自动注入
Car car;
@Test
public void funTest(){
System.out.println(car);
}
}
控制台打印输出
log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Car [name=咖菲猫, color=blue]
如果出现了这个异常
Causedby:java.lang.NoSuchMethodError:org.springframework.cache.ehcache.EhCacheFactoryBean.setMaxEntriesLocalHeap(J)V
at org.springframework.cache.ehcache.EhCacheFactoryBean.<init>(EhCacheFactoryBean.java:101)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
... 75 more
请先注释掉,具体原因还没有找到,也可以调其他版本