복붙노트

[SPRING] 스프링 유닛 테스트 중에 ApplicationContext를로드하지 못했습니다.

SPRING

스프링 유닛 테스트 중에 ApplicationContext를로드하지 못했습니다.

내 응용 프로그램 컨텍스트 스프링 자바 - 구성을 사용하여 Junit 기능 테스트를 실행하려고합니다. 나는 Spring이나 Junit에 문제가 있는지 잘 모르겠다. 확실하지 않다. (db를 치는) 내 로컬 서버에서 애플리케이션이 잘 돌아 가지 만, 내 테스트를 실행하려고하면 폭탄이 튀어 나온다. 난 그냥 내 xml 컨텍스트 파일을 가져올 수 있도록 XML 구성을 Java로 이동 (내 테스트에서 작동하는지 알고 있지만) 앞으로 오히려 그냥 내 Java 구성 사용합니다.

내 테스트 클래스

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
        classes = { AppConfig.class, ServletConfig.class })
@EnvironmentConfiguration(db2Enabled = true)
public class EventDAOTest {

StackTrace

Feb 4, 2014 11:51:45 AM com.aoins.config.CachingPropertyFileReader <clinit>
SEVERE: ERROR - Configuration Framework not detected!
Feb 4, 2014 11:51:45 AM com.aoins.config.CachingPropertyFileReader readFile
SEVERE: Unable to build property reference for: (common).
2014-02-04 11:51:45,510 | DEBUG |         : | LoggerConfigurer | Msg: Log4j configured with: 'C:/javalog/log4jPCProperties.xml'
2014-02-04 11:51:48,248 | INFO  |         : | EnvironmentConfigurer | Msg: DB2 Connection was established
2014-02-04 11:51:48,279 | INFO  |         : | EnvironmentConfigurer | Msg: CICS Connection was established
2014-02-04 11:51:48,279 | INFO  |         : | EnvironmentConfigurer | Msg: JMS Connection was NOT established according to the configuration
2014-02-04 11:51:48,279 | INFO  |         : | EnvironmentConfigurer | Msg: EMail Connection was NOT established according to the configuration
Feb 4, 2014 11:51:48 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@215d215d: startup date [Tue Feb 04 11:51:48 EST 2014]; root of context hierarchy
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/associates],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.associate.AssociateDataController.retrieveAssociates(java.lang.String)
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/associateFilterTypes],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.associatefiltertype.AssociateFilterDataController.retrieveEventFilterTypes()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/associateFilterTypes/{pTypeCode}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.associatefiltertype.AssociateFilterDataController.retrieveEventFilterType(java.lang.String) throws com.aoins.sales.eventplanning.associatefiltertype.AssociateFilterTypeNotFoundException
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/dateFilterTypes],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.datefiltertype.DateFilterDataController.retrieveEventFilterTypes()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/dateFilterTypes/{pTypeCode}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.datefiltertype.DateFilterDataController.retrieveEventFilterType(java.lang.String) throws com.aoins.sales.eventplanning.datefiltertype.DateFilterTypeNotFoundException
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/departments/{pDepartmentCode}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.department.DepartmentDataController.retrieveDepartment(java.lang.String) throws com.aoins.sales.eventplanning.department.DepartmentNotFoundException
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/divisions],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.division.DivisionDataController.retrieveDivisionsDepartments()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.aoins.sales.eventplanning.events.EventController.showEvents()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[//Test],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.aoins.sales.eventplanning.events.EventController.showTests()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/events/{pEventId}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.events.EventDataController.retrieveEvent(java.lang.Integer)
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/events],methods=[GET],params=[page && associateFilter && dateFilter],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.events.EventDataController.retrieveFiltered(com.aoins.sales.eventplanning.associatefiltertype.AssociateFilterType,com.aoins.sales.eventplanning.datefiltertype.DateFilterType,java.lang.Integer,com.aoins.sales.user.User)
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/events],methods=[POST],params=[],headers=[],consumes=[application/json],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.events.EventDataController.saveEvent(com.aoins.sales.eventplanning.events.EventBeanImpl,com.aoins.sales.user.User) throws com.aoins.sales.eventplanning.events.EventException
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/Public/events],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public java.util.List<com.aoins.sales.eventplanning.events.Event> com.aoins.sales.eventplanning.events.EventDataPublicController.doList()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/Public/events/{pEventId}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public com.aoins.sales.eventplanning.events.Event com.aoins.sales.eventplanning.events.EventDataPublicController.doRetrieve(java.lang.Integer)
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/eventTypes],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.eventtype.EventTypeDataController.retrieveEventTypes()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/eventTypes/{pTypeCode}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.eventtype.EventTypeDataController.retrieveEventType(java.lang.String) throws com.aoins.sales.eventplanning.eventtype.EventTypeNotFoundException
Feb 4, 2014 11:51:49 AM org.springframework.test.context.TestContextManager prepareTestInstance
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@20c820c8] to prepare test instance [com.aoins.sales.eventplanning.events.EventDAOTest@f7e0f7e]
Throwable occurred: java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:326)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:212)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
    at com.aoins.func.tester.AOSpringFunctionalTester.run(AOSpringFunctionalTester.java:48)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.HandlerMapping org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping()] threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:592)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:121)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
    ... 26 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.HandlerMapping org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping()] threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581)
    ... 41 more
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
    at java.lang.Throwable.<init>(Throwable.java:67)
    at org.springframework.util.Assert.notNull(Assert.java:111)
    at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:54)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:330)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$104f0b6f.CGLIB$defaultServletHandlerMapping$22(<generated>)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$104f0b6f$$FastClassByCGLIB$$ff8cbba8.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:326)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$104f0b6f.defaultServletHandlerMapping(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:611)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
    ... 42 more

그래서 그것은 구성 프레임 워크를 찾지 못하는 것 같습니다,하지만 참조 가이드 및 API를 따라 왔습니다 ... 내가 무엇을 놓치고 있는지, 올바르게 구성하지 않았는지 확실하지 않습니다. 나는 Spring 4.0, Junit 4.10을 사용하고있다.

또한 각 테스트마다이 오류가 발생합니다. 그게 내 ApplicationContext를 다시 (prepareRefresh)로드하려고 ... 한 번 @Test 각 - 그게 나에게 이해가되지 않는다는 것을 의미합니다 ...

다음은 몇 가지 자료입니다.

해결법

  1. ==============================

    1.테스트 클래스에 주석을 달아야합니다.

    테스트 클래스에 주석을 달아야합니다.

    @WebAppConfiguration
    

    테스트 환경은 WebApplicationContext에 MVC 구성에 필요한 mock ServletContext를 제공합니다.

  2. ==============================

    2.스프링 3.2.0에서 4.0.3으로 옮겨서 서블릿 2.5에서 서블릿 3.0.1로 javax.servlet 의존성 (Maven에서)을 업데이트해야했다. 최종 종속성은

    스프링 3.2.0에서 4.0.3으로 옮겨서 서블릿 2.5에서 서블릿 3.0.1로 javax.servlet 의존성 (Maven에서)을 업데이트해야했다. 최종 종속성은

           <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.0.1</version>
           </dependency>
    

    그런 다음 효과가있었습니다.

  3. ==============================

    3.몇 사람이 서블릿 버전 문제를 언급 한 이래로 :

    몇 사람이 서블릿 버전 문제를 언급 한 이래로 :

    Spring 4.0에서 mock 세트는 이제 Servlet 3.0 API를 기반으로합니다.

    두 가지 옵션이 있습니다.

    
        <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-test</artifactId>
           <version>3.2.14.RELEASE</version>
           <scope>test</scope>
        </dependency>
    
    
    
        <dependency>
           <groupId>javax.servlet</groupId>
           <artifactId>javax.servlet-api</artifactId>
           <version>3.0.1</version>
        </dependency>
    
    
  4. ==============================

    4.In gradle

    In gradle

    testCompile 'javax.servlet:javax.servlet-api:3.1.0'
    

    참고 :이 테스트는 Google App Engine (서블릿 2.4)을 테스트하는 경우에도 작동합니다. 테스트에만 사용되기 때문입니다.

    https://jira.spring.io/browse/SPR-11049

  5. ==============================

    5.그러한 문제를 해결하는 방법 - 다음과 같이 수동으로 notFoundClass를 강제로 가져 오십시오. 클래스 c = javax.servlet.SessionCookieConfig.class;

    그러한 문제를 해결하는 방법 - 다음과 같이 수동으로 notFoundClass를 강제로 가져 오십시오. 클래스 c = javax.servlet.SessionCookieConfig.class;

    그래서 Idea + Maven은 Maven 의존성을 추가 할 것을 제안했습니다. 그리고 갑자기 pom.xml에 코드가 나타납니다.

        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-servlet_3.0_spec</artifactId>
            <version>1.0</version>
            <scope>test</scope>
        </dependency>
    

    그런 다음 "Class c = javax.servlet.SessionCookieConfig.class;"를 제거했습니다. - 필요한 종속성을로드하는 것보다는 그 안에 필요가 없습니다.

  6. ==============================

    6.테스트 applicationContext에 MockServletContext를 추가 할 수 있습니다. MockServletContext는 spring-test.jar (또는 Maven 종속성)에서 찾을 수 있습니다. 프로덕션 환경에서는 이것을 사용하지 말고 테스트 컨텍스트에 포함시키는 컨텍스트에서만 등록해야합니다.

    테스트 applicationContext에 MockServletContext를 추가 할 수 있습니다. MockServletContext는 spring-test.jar (또는 Maven 종속성)에서 찾을 수 있습니다. 프로덕션 환경에서는 이것을 사용하지 말고 테스트 컨텍스트에 포함시키는 컨텍스트에서만 등록해야합니다.

  7. ==============================

    7.@ActiveProfiles ({ "{test", "default"}) 주석 사용

    @ActiveProfiles ({ "{test", "default"}) 주석 사용

  8. from https://stackoverflow.com/questions/21561432/failed-to-load-applicationcontext-during-spring-unit-test by cc-by-sa and MIT license