Spring整合Junit4进行单元测试

一.加入依赖包

使用spring的测试框架需要加入以下依赖包:
JUnit 4 (官方下载:http://www.junit.org/
Spring Test (Spring框架中的test包)
Spring 相关其他依赖包(不再赘述了,就是context等包)

如果使用maven,在基于spring的项目中添加如下依赖:

[html]  view plain  copy
  1. <dependency>  
  2.             <groupId>junitgroupId>  
  3.             <artifactId>junitartifactId>  
  4.             <version>4.9version>  
  5.             <scope>testscope>  
  6. dependency>   
  7. <dependency>  
  8.             <groupId>org.springframeworkgroupId>  
  9.             <artifactId>spring-testartifactId>  
  10.             <version> 3.2.4.RELEASE  version>  
  11.             <scope>providedscope>  
  12. dependency>   

二.创建测试类

1)基类,其实就是用来加载配置文件的 

[java]  view plain  copy
  1. package Solin.Test;  
  2.   
  3. import org.junit.runner.RunWith;  
  4. import org.springframework.test.context.ContextConfiguration;  
  5. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  6.   
  7. @RunWith(SpringJUnit4ClassRunner.class//使用junit4进行测试  
  8. @ContextConfiguration(locations={"classpath:applicationContext.xml"}) //加载配置文件   
  9. //------------如果加入以下代码,所有继承该类的测试类都会遵循该配置,也可以不加,在测试类的方法上///控制事务,参见下一个实例    
  10. //这个非常关键,如果不加入这个注解配置,事务控制就会完全失效!    
  11. //@Transactional    
  12. //这里的事务关联到配置文件中的事务控制器(transactionManager = "transactionManager"),同时//指定自动回滚(defaultRollback = true)。这样做操作的数据才不会污染数据库!    
  13. //@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)    
  14. //------------    
  15. public class BaseJunit4Test{  
  16.       
  17. }  

解释下用到的注解:
@RunWith:用于指定junit运行环境,是junit提供给其他框架测试环境接口扩展,为了便于使用spring的依赖注入,spring提供了org.springframework.test.context.junit4.SpringJUnit4ClassRunner作为Junit测试环境
@ContextConfiguration({"classpath:applicationContext.xml","classpath:spring/buyer/applicationContext-service.xml"}) 
导入配置文件,这里我的applicationContext配置文件是根据模块来分类的。如果有多个模块就引入多个“applicationContext-service.xml”文件。如果所有的都是写在“applicationContext。xml”中则这样导入: 
@ContextConfiguration(locations = "classpath:applicationContext.xml") 
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)这里的事务关联到配置文件中的事务控制器(transactionManager = "transactionManager"),同时指定自动回滚(defaultRollback = true)。这样做操作的数据才不会污染数据库! 
@Transactional:这个非常关键,如果不加入这个注解配置,事务控制就会完全失效! 

AbstractTransactionalDataSourceSpringContextTests要想构建这一系列的无污染纯绿色事务测试框架就必须找

到这个基类!(即所有事务均不生效)

2)接着是我们自己的测试类 
[java]  view plain  copy
  1. package Solin.Test;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.junit.Test;  
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.test.annotation.Rollback;  
  8. import org.springframework.transaction.annotation.Transactional;  
  9.   
  10. import Solin.Entity.ImageInfo;  
  11. import Solin.Service.ImageInfoService;  
  12.   
  13. public class ImageInfoTest extends BaseJunit4Test{  
  14.     @Autowired //自动注入  
  15.     private ImageInfoService imageInfoService;  
  16.       
  17.     @Test  
  18.     @Transactional   //标明此方法需使用事务    
  19.     @Rollback(false)  //标明使用完此方法后事务不回滚,true时为回滚   
  20.     public void test(){  
  21.         System.out.println("测试Spring整合Junit4进行单元测试");  
  22.           
  23.         ImageInfo imageInfo = new ImageInfo();  
  24.         imageInfo.setParentID(999);  
  25.         imageInfo.setImgAddr("地球");  
  26.         imageInfoService.saveImageInfo(imageInfo);  
  27.           
  28.         List list = imageInfoService.getImageInfoList(95);  
  29.         for(ImageInfo img : list){  
  30.             System.out.println("parentID:"+img.getParentID()+"------imgAddr:"+img.getImgAddr());  
  31.         }  
  32.     }  
  33. }  

.通过JUnit 4 执行

右键方法名,选择则“Run As”→“JUnit Test”即可

---------------------------------------------------------------------------------------------------------------------

然而当我执行时却报了第一个错误(之所以说是第一个是因为后面还有其他错误),错误内容如下:

[java]  view plain  copy
  1. java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing  
  2.     at java.lang.ClassLoader.defineClass1(Native Method)  
  3.     at java.lang.ClassLoader.defineClass(Unknown Source)  
  4.     at java.security.SecureClassLoader.defineClass(Unknown Source)  
  5.     at java.net.URLClassLoader.defineClass(Unknown Source)  
  6.     at java.net.URLClassLoader.access$100(Unknown Source)  
  7.     at java.net.URLClassLoader$1.run(Unknown Source)  
  8.     at java.net.URLClassLoader$1.run(Unknown Source)  
  9.     at java.security.AccessController.doPrivileged(Native Method)  
  10.     at java.net.URLClassLoader.findClass(Unknown Source)  
  11.     at java.lang.ClassLoader.loadClass(Unknown Source)  
  12.     at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)  
  13.     at java.lang.ClassLoader.loadClass(Unknown Source)  
  14.     at java.lang.Class.getDeclaredConstructors0(Native Method)  
  15.     at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)  
  16.     at java.lang.Class.getConstructor0(Unknown Source)  
  17.     at java.lang.Class.getConstructor(Unknown Source)  
  18.     at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:29)  
  19.     at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:21)  
  20.     at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)  
  21.     at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)  
  22.     at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)  
  23.     at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:26)  
  24.     at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)  
  25.     at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)  
  26.     at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)  
  27.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)  
  28.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)  
  29.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)  
  30.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)  
  31. Caused by: java.lang.ClassNotFoundException: org.hamcrest.SelfDescribing  
  32.     at java.net.URLClassLoader$1.run(Unknown Source)  
  33.     at java.net.URLClassLoader$1.run(Unknown Source)  
  34.     at java.security.AccessController.doPrivileged(Native Method)  
  35.     at java.net.URLClassLoader.findClass(Unknown Source)  
  36.     at java.lang.ClassLoader.loadClass(Unknown Source)  
  37.     at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)  
  38.     at java.lang.ClassLoader.loadClass(Unknown Source)  
  39.     ... 29 more  
上网查了一下,一般的解决方案是,换一个低一点的版本就好了。还有人说,是缺少hamcrest的包。去官网又看了一下,结果发现这样一段话:
junit.jar: Includes the Hamcrest classes. The simple all-in-one solution to get started quickly.Starting with version 4.11, Hamcrest is no longer included in this jar.
junit-dep.jar: Only includes the JUnit classes but not Hamcrest. Lets you use a different Hamcrest version.
注意部分的字,说明4.1.1中没有hamcrest包了。

最好的解决方法是:
使用是导入包的方案:junit.jar + hamcrest-core.jar + hamcrest-library.jar或者是:junit-dep.ajr+hancrest-all.jar

再次运行,又报错了,错误如下:

[java]  view plain  copy
  1. java.lang.IllegalStateException: Failed to load ApplicationContext  
  2.     at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)  
  3.     at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)  
  4.     at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)  
  5.     at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)  
  6.     at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:307)  
  7.     at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)  
  8.     at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)  
  9.     at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)  
  10.     at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)  
  11.     at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)  
  12.     at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)  
  13.     at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)  
  14.     at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)  
  15.     at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)  
  16.     at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)  
  17.     at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)  
  18.     at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)  
  19.     at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)  
  20.     at org.junit.runners.ParentRunner.run(ParentRunner.java:309)  
  21.     at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)  
  22.     at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)  
  23.     at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)  
  24.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)  
  25.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)  
  26.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)  
  27.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)  
  28. Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [E:\workspace\ExpenseReimbursement\build\classes\Solin\Entity\ExpenseDetail.class]; nested exception is org.springframework.core.NestedIOException: ASM ClassReader failed to parse class file - probably due to a new Java class file version that isn't supported yet: file [E:\workspace\ExpenseReimbursement\build\classes\Solin\Entity\ExpenseDetail.class]; nested exception is java.lang.IllegalArgumentException  
  29.     at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:290)  
  30.     at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:242)  
  31.     at org.springframework.context.annotation.ComponentScanBeanDefinitionParser.parse(ComponentScanBeanDefinitionParser.java:84)  
  32.     at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73)  
  33.     at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1438)  
  34.     at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1428)  
  35.     at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:195)  
  36.     at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:139)  
  37.     at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:108)  
  38.     at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)  
  39.     at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)  
  40.     at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)  
  41.     at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)  
  42.     at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)  
  43.     at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)  
  44.     at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)  
  45.     at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243)  
  46.     at org.springframework.test.context.support.AbstractGenericContextLoader.loadBeanDefinitions(AbstractGenericContextLoader.java:233)  
  47.     at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:117)  
  48.     at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)  
  49.     at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)  
  50.     at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)  
  51.     at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)  
  52.     at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)  
  53.     ... 25 more  
  54. Caused by: org.springframework.core.NestedIOException: ASM ClassReader failed to parse class file - probably due to a new Java class file version that isn't supported yet: file [E:\workspace\ExpenseReimbursement\build\classes\Solin\Entity\ExpenseDetail.class]; nested exception is java.lang.IllegalArgumentException  
  55.     at org.springframework.core.type.classreading.SimpleMetadataReader.(SimpleMetadataReader.java:56)  
  56.     at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)  
  57.     at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102)  
  58.     at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:266)  
  59.     ... 48 more  
  60. Caused by: java.lang.IllegalArgumentException  
  61.     at org.springframework.asm.ClassReader.(Unknown Source)  
  62.     at org.springframework.asm.ClassReader.(Unknown Source)  
  63.     at org.springframework.asm.ClassReader.(Unknown Source)  
  64.     at org.springframework.core.type.classreading.SimpleMetadataReader.(SimpleMetadataReader.java:53)  
  65.     ... 51 more  
一点点搜吧,万能的stackoverflow啊,哈哈,老外同仁给出的解释:

Note that the Java 8 bytecode level (-target 1.8, as required by -source 1.8) is only fully supported as of Spring Framework 4.0. In particular, Spring 3.2 based applications need to be compiled with a maximum of Java 7 as the target, even if they happen to be deployed onto a Java 8 runtime. Please upgrade to Spring 4 for Java 8 based applications.

大概的意思就是java1.8版本只支持spring4.0以上。所以解决方法有2中①把sping版本换成4.0以上②把jdk调低点。

此处我选择把jdk调低点,再次运行,结果如下:

[java]  view plain  copy
  1. 测试Spring整合Junit4进行单元测试  
  2. parentID:95------imgAddr:广东深圳  
  3. parentID:95------imgAddr:广东深圳  

你可能感兴趣的:(Java)