项目框架:spring mvc + mybatis + shiro
spring 4.1.9
想写一个service层测试
代码:
package com.chnskin.test.vd;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.chnskin.common.persistence.Page;
import com.chnskin.modules.wms.entity.VdGoodsPrice;
import com.chnskin.modules.wms.service.VdGoodsPriceService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { “classpath*:spring-context.xml” })
public class VdGoodsPriceTest {
@Resource
private VdGoodsPriceService vdGoodsPriceService;
@Test
public void findPageNew() {
Page page = new Page();
VdGoodsPrice vdGoodsPrice = new VdGoodsPrice();
Page page2 = vdGoodsPriceService.findPageNew(page, vdGoodsPrice);
System.out.println(page2.getTotalPage());
System.out.println(page2.getCount());
}
}
第一次报错
2017-09-21 14:13:30,877 WARN [org.springframework.context.support.GenericApplicationContext] - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘shiroFilter’ defined in URL [file:/C:/Users/9003286.FMKEJI/git/vendor/src/main/webapp/WEB-INF/classes/spring-context-shiro.xml]: Cannot resolve reference to bean ‘securityManager’ while setting bean property ‘securityManager’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘securityManager’ defined in URL [file:/C:/Users/9003286.FMKEJI/git/vendor/src/main/webapp/WEB-INF/classes/spring-context-shiro.xml]: Cannot resolve reference to bean ‘systemAuthorizingRealm’ while setting bean property ‘realm’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘systemAuthorizingRealm’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: javax.servlet.http.HttpServletRequest com.chnskin.modules.sys.security.SystemAuthorizingRealm.request; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.servlet.http.HttpServletRequest] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-09-21 14:13:30,902 ERROR [org.springframework.test.context.TestContextManager] - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@559e9961] to prepare test instance [com.chnskin.test.vd.VdGoodsPriceTest@1f67db31]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:94)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:72)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner 1.runReflectiveCall(SpringJUnit4ClassRunner.java:259)atorg.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:261)atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:219)atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)atorg.junit.runners.ParentRunner 3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner 1.schedule(ParentRunner.java:63)atorg.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)atorg.junit.runners.ParentRunner.access 000(ParentRunner.java:53)
at org.junit.runners.ParentRunner 2.evaluate(ParentRunner.java:229)atorg.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)atorg.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)atorg.junit.runners.ParentRunner.run(ParentRunner.java:309)atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)atorg.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)atorg.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)atorg.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)atorg.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)atorg.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)atorg.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)Causedby:org.springframework.beans.factory.BeanCreationException:Errorcreatingbeanwithname‘shiroFilter′definedinURL[file:/C:/Users/9003286.FMKEJI/git/vendor/src/main/webapp/WEB−INF/classes/spring−context−shiro.xml]:Cannotresolvereferencetobean‘securityManager′whilesettingbeanproperty‘securityManager′;nestedexceptionisorg.springframework.beans.factory.BeanCreationException:Errorcreatingbeanwithname‘securityManager′definedinURL[file:/C:/Users/9003286.FMKEJI/git/vendor/src/main/webapp/WEB−INF/classes/spring−context−shiro.xml]:Cannotresolvereferencetobean‘systemAuthorizingRealm′whilesettingbeanproperty‘realm′;nestedexceptionisorg.springframework.beans.factory.BeanCreationException:Errorcreatingbeanwithname‘systemAuthorizingRealm′:Injectionofautowireddependenciesfailed;nestedexceptionisorg.springframework.beans.factory.BeanCreationException:Couldnotautowirefield:javax.servlet.http.HttpServletRequestcom.chnskin.modules.sys.security.SystemAuthorizingRealm.request;nestedexceptionisorg.springframework.beans.factory.NoSuchBeanDefinitionException:Noqualifyingbeanoftype[javax.servlet.http.HttpServletRequest]foundfordependency:expectedatleast1beanwhichqualifiesasautowirecandidateforthisdependency.Dependencyannotations:@org.springframework.beans.factory.annotation.Autowired(required=true)atorg.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)atorg.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1475)atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1220)atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)atorg.springframework.beans.factory.support.AbstractBeanFactory 1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:232)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:619)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:465)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:109)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:261)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:68)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:86)
… 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘securityManager’ defined in URL [file:/C:/Users/9003286.FMKEJI/git/vendor/src/main/webapp/WEB-INF/classes/spring-context-shiro.xml]: Cannot resolve reference to bean ‘systemAuthorizingRealm’ while setting bean property ‘realm’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘systemAuthorizingRealm’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: javax.servlet.http.HttpServletRequest com.chnskin.modules.sys.security.SystemAuthorizingRealm.request; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.servlet.http.HttpServletRequest] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1475)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1220)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
… 43 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘systemAuthorizingRealm’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: javax.servlet.http.HttpServletRequest com.chnskin.modules.sys.security.SystemAuthorizingRealm.request; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.servlet.http.HttpServletRequest] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1208)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory 1.getObject(AbstractBeanFactory.java:303)atorg.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)atorg.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)atorg.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)atorg.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)…53moreCausedby:org.springframework.beans.factory.BeanCreationException:Couldnotautowirefield:javax.servlet.http.HttpServletRequestcom.chnskin.modules.sys.security.SystemAuthorizingRealm.request;nestedexceptionisorg.springframework.beans.factory.NoSuchBeanDefinitionException:Noqualifyingbeanoftype[javax.servlet.http.HttpServletRequest]foundfordependency:expectedatleast1beanwhichqualifiesasautowirecandidateforthisdependency.Dependencyannotations:@org.springframework.beans.factory.annotation.Autowired(required=true)atorg.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
… 61 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.servlet.http.HttpServletRequest] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
… 63 more
主要原因:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.servlet.http.HttpServletRequest] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
查找了下源码 确实存在HttpServltRequest的引用
找了半天的
结果在
https://stackoverflow.com/questions/17619029/spring-junit-test-case-failed
发现原因
The error is in the stack trace
Could not autowire field: private javax.servlet.http.HttpServletRequest com.myapp.controller.ProductController.request; … No matching bean of type [javax.servlet.http.HttpServletRequest]
The problem is that simple Spring tests run with the bare Spring apprlication context, without Spring Web Application context capabilities. So HttpServletRequests, Servlet Context and other features are not available in this case.
Try adding @WebAppConfiguration annotation to the test class.
Please note, that this option is available only in Spring 3.2+ versions.
In the older versions of Spring you’ll need to invent something to make this interface implementations available in the application context(the most straightforward thing is to expose MockServletContext class and/or HttpServletRequest interface as beans for tests).
Also please note that the code that uses session scope beans is usually controller specific and belongs to web application context and I believe that it will be the best practice to test controllers in separate tests with the @WebAppConfiguration, but leave the tests of the plain old beans and services belonging to the root application context in the simple application contexts, i.e. without @WebAppConfiguration.
Just to be clear ProductDAO belongs to the root application context, and ProductController belongs to the web application context, so their definitions should be placed in different xml files. ProductDAO test should point to the xml of the root app context only and contain no @WebAppConfiguration.
As for ProductController test should point to both root app context and web app context xml files (see How to Setup web application context in Spring MVC test for examples) and be annotated with @WebAppConfiguration
加上@WebAppConfiguration
原以为可以了 ,结果又报另一个错误
第二个
java.lang.NoClassDefFoundError: javax/servlet/SessionCookieConfig
at org.springframework.test.context.web.AbstractGenericWebContextLoader.configureWebResources(AbstractGenericWebContextLoader.java:200)
at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:127)
at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:109)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:261)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:68)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:86)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:72)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:170)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:110)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner 1.runReflectiveCall(SpringJUnit4ClassRunner.java:259)atorg.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:261)atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:219)atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)atorg.junit.runners.ParentRunner 3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner 1.schedule(ParentRunner.java:63)atorg.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)atorg.junit.runners.ParentRunner.access 000(ParentRunner.java:53)
at org.junit.runners.ParentRunner 2.evaluate(ParentRunner.java:229)atorg.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)atorg.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)atorg.junit.runners.ParentRunner.run(ParentRunner.java:309)atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)atorg.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)atorg.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)atorg.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)atorg.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)atorg.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)atorg.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)Causedby:java.lang.ClassNotFoundException:javax.servlet.SessionCookieConfigatjava.net.URLClassLoader 1.run(URLClassLoader.java:366)
at java.net.URLClassLoader 1.run(URLClassLoader.java:355)atjava.security.AccessController.doPrivileged(NativeMethod)atjava.net.URLClassLoader.findClass(URLClassLoader.java:354)atjava.lang.ClassLoader.loadClass(ClassLoader.java:425)atsun.misc.Launcher AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
… 32 more
主要原因:
java.lang.NoClassDefFoundError: javax/servlet/SessionCookieConfig
解决方法:
请参考:
http://www.cnblogs.com/TonyYPZhang/p/5185386.html
主要是