title: @ContextConfiguration for JUnit (configuration from /webapp)
body: <p>Good day all.</p>
  
  <p>Writting JUnit test for my Spring app meet with the next problem. 
  My standart Context Configuration files storage on the project in /webapp (that don't part of classpath for Unit test).</p>
  
  <p>project structure:
  <a href="https://i.stack.imgur.com/8JN0f.png" rel="nofollow noreferrer">project structure</a></p>
  
  <p>JUnit test:</p>
  
  <pre><code>    @RunWith(SpringJUnit4ClassRunner.class)
  @ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/config/application-context.xml", "file:src/main/webapp/WEB-INF/config/mvc-config.xml"})
  public class AdvertORMServiceTest {
  
      @Autowired
      private AdvertORMService jpaAdvertORMService;
  
      @Test
      public void queryAllAdvertsTest() {
          List&lt;Advert&gt; adverts = jpaAdvertORMService.findAll();
          Assert.assertNotNull(adverts);
      }
  
  }
  </code></pre>
  
  <p>application-context.xml:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:mvc="http://www.springframework.org/schema/mvc"
         xmlns:context="http://www.springframework.org/schema/context"
         xmlns:jpa="http://www.springframework.org/schema/data/jpa"
         xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"&gt;
  
  
      &lt;context:property-placeholder location="classpath:util.properties" /&gt;
      &lt;!--Activates various annotations to be detected in bean classes: Spring's @Required and @Autowired and so on--&gt;
      &lt;context:annotation-config/&gt;
  
      &lt;!-- Datasource.  -  MySQL --&gt;
      &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
          &lt;property name="driverClassName" value="${jdbc.driverClass}"/&gt;
          &lt;property name="url" value="${jdbc.url}" /&gt;
          &lt;property name="username" value="${jdbc.username}"/&gt;
          &lt;property name="password" value="${jdbc.password}" /&gt;
      &lt;/bean&gt;
  
      &lt;!--Do not forget activate @Transactional JPA annotation with &lt;annotation-driven/&gt;--&gt;
      &lt;!-- JPA Persistence Context and EntityManager configuration --&gt;
      &lt;bean id="entityManagerFactory"
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" &gt;
          &lt;!--packagesToScan - search Entity and mapping them --&gt;
          &lt;property name="packagesToScan" value="by.GetItFree" /&gt;
          &lt;property name="dataSource" ref="dataSource" /&gt;
          &lt;property name="jpaVendorAdapter"&gt;
              &lt;bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" &gt;
                  &lt;property name="generateDdl" value="true" /&gt;
                  &lt;property name="showSql" value="true" /&gt;
              &lt;/bean&gt;
          &lt;/property&gt;
          &lt;property name="jpaProperties"&gt;
              &lt;props&gt;
                  &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQL5Dialect&lt;/prop&gt;
                  &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt;
                  &lt;prop key="hibernate.format_sql"&gt;false&lt;/prop&gt;
                  &lt;prop key="hibernate.hbm2ddl.auto"&gt;update&lt;/prop&gt;
                  &lt;!--it's anti pattern need to delete it, and solv exception:--&gt;
                  &lt;!--failed to lazily initialize a collection of role could not initialize proxy - no Session--&gt;
                  &lt;!--&lt;prop key="hibernate.enable_lazy_load_no_trans"&gt;true&lt;/prop&gt;--&gt;
              &lt;/props&gt;
          &lt;/property&gt;
      &lt;/bean&gt;
  
      &lt;!-- Automatic Transaction Participation--&gt;
      &lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt;
          &lt;property name="entityManagerFactory" ref="entityManagerFactory" /&gt;
      &lt;/bean&gt;
  
      &lt;jpa:repositories base-package="by.GetItFree.orm.repository" entity-manager-factory-ref="entityManagerFactory"
                        transaction-manager-ref="transactionManager"/&gt;
  
  
      &lt;!-- REST template configuration --&gt;
      &lt;bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/&gt;
  
  &lt;/beans&gt;
  
  **mvc-config.xml:**
  
  
  
     &lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:mvc="http://www.springframework.org/schema/mvc"
         xmlns:context="http://www.springframework.org/schema/context"
         xmlns:tx="http://www.springframework.org/schema/tx"
         xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"&gt;
  
      &lt;!-- context:component-scan This tag will scan @Component, @Repository, @Service, @Controller
           and also resolves @Autowired and @Qualifier --&gt;
      &lt;context:component-scan base-package="by.GetItFree"/&gt;
  
      &lt;!--
          mvc:annotation-driven configures Spring MVC annotations
          Support for validating @Controller inputs with @Valid, if a JSR-303 Provider is present on the classpath.
          HttpMessageConverter support for @RequestBody method parameters and @ResponseBody method return values
          from @RequestMapping or @ExceptionHandler methods.
       --&gt;
      &lt;mvc:annotation-driven/&gt;
  
      &lt;!-- activate @Transactional JPA annotation --&gt;
      &lt;tx:annotation-driven/&gt;
  
      &lt;!-- ViewResolver bean config for mapping strings to jsp views --&gt;
      &lt;bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;
          &lt;!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' --&gt;
          &lt;property name="order" value="1"/&gt;
          &lt;property name="prefix" value="/WEB-INF/view"/&gt;
          &lt;property name="suffix" value=".jsp"/&gt;
      &lt;/bean&gt;
  
  
      &lt;mvc:view-controller path="/about.html" view-name="/about/about"/&gt;
      &lt;mvc:view-controller path="/index.html" view-name="/index"/&gt;
  
      &lt;mvc:view-controller path="/" view-name="/index"/&gt;
  
  
      &lt;!-- Static Resources Configuration (get access to static sources such as CSS and JavaScript files) --&gt;
      &lt;mvc:resources mapping="/resources/**" location="/resources/"/&gt;
  
      &lt;mvc:interceptors&gt;
  
          &lt;mvc:interceptor&gt;
              &lt;mvc:mapping path="/**"/&gt;
              &lt;bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"&gt;
                  &lt;property name="paramName" value="languageVar"/&gt;
              &lt;/bean&gt;
          &lt;/mvc:interceptor&gt;
      &lt;/mvc:interceptors&gt;
  
      &lt;bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"&gt;
          &lt;property name="defaultLocale" value="ru"/&gt;
          &lt;!-- cookieMaxAge in seconds. if you set it to -1, the cookie will be deleted when browser is closed) --&gt;
          &lt;property name="cookieMaxAge" value="100000"/&gt;
      &lt;/bean&gt;
  
      &lt;!-- MessageSource ReloadableResourceBundleMessageSource configuration --&gt;
      &lt;bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"&gt;
          &lt;property name="basenames" value="classpath:/locales/messages,classpath:util"/&gt;
          &lt;property name="cacheSeconds" value="1"/&gt;
          &lt;property name="defaultEncoding" value="UTF-8"/&gt;
      &lt;/bean&gt;
  
      &lt;!--
       mvc:annotation-driven configures Spring MVC annotations
       Support for validating @Controller inputs with @Valid, if a JSR-303 Provider is present on the classpath.
       HttpMessageConverter support for @RequestBody method parameters and @ResponseBody method return values
       from @RequestMapping or @ExceptionHandler methods.
      --&gt;
      &lt;mvc:annotation-driven&gt;
          &lt;!--use int RestController to produce pretty json response--&gt;
          &lt;mvc:message-converters&gt;
              &lt;bean id="jacksonHttpMessageConverter"
                    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"&gt;
                  &lt;property name="prettyPrint" value="true"/&gt;
              &lt;/bean&gt;
          &lt;/mvc:message-converters&gt;
      &lt;/mvc:annotation-driven&gt;
  &lt;/beans&gt;
  </code></pre>
  
  <p><strong>Stack trace:</strong></p>
  
  <pre><code>    java.lang.IllegalStateException: Failed to load ApplicationContext
      at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
      at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
      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:230)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
      at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
      at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
      at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
      at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
      at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
      at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
      at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
      at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
      at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
      at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
      at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
      at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
      at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
      at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
      at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
      at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
  Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@12ad1b2a]]] does not run in a WebApplicationContext but in: org.springframework.context.support.GenericApplicationContext@536aaa8d: startup date [Fri Mar 10 00:42:32 MSK 2017]; root of context hierarchy
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
      at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
      at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
      at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
      at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
      at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
      at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
      at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
      ... 31 more
  Caused by: java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@12ad1b2a]]] does not run in a WebApplicationContext but in: org.springframework.context.support.GenericApplicationContext@536aaa8d: startup date [Fri Mar 10 00:42:32 MSK 2017]; root of context hierarchy
      at org.springframework.web.context.support.WebApplicationObjectSupport.getWebApplicationContext(WebApplicationObjectSupport.java:112)
      at org.springframework.web.context.support.WebApplicationObjectSupport.getServletContext(WebApplicationObjectSupport.java:128)
      at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.initContentNegotiationStrategy(ResourceHttpRequestHandler.java:306)
      at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.afterPropertiesSet(ResourceHttpRequestHandler.java:268)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
      ... 46 more
  Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 5.006 sec &lt;&lt;&lt; FAILURE!
  </code></pre>
  
  <p>Thanks for attention.</p>
  
  <p>github link to the project: <a href="https://github.com/nolik/GetITFree" rel="nofollow noreferrer">project on github</a></p>