Spring MVC REST Controller测试不会自动装配WebApplicationContext

时间:2013-07-30 18:03:16

标签: unit-testing rest spring-mvc controller junit4

Spring 3.2.3.Release and Junit4 4.11

我创建了一个Web应用程序Spring MVC REST项目。这是一个项目,它具有围绕服务和域实体的控制器。来自其他项目的DAO和服务都经过单元测试并且工作正常,因此这不是问题。 DAO和服务来自编译的jar文件。

我正在使用maven,所以我确实有Spring-web,Spring-webmvc,Spring Core,Spring-Beans,Spring-test ...... Spring-test是3.2.3.Release版本,而不是单独的GitHub版本

我花了两天的时间看着互联网,谷歌和StackOverflow,以及春季论坛获得明确的答案,但我无法得到我需要的确切答案,所以我需要另外一组眼睛来看待在我的文件中看看是否有什么问题。

问题是我的单元测试不起作用,它非常小,但是出现了很大的错误,我根本无法执行任何测试。所以,让我开始列出我的代码和xml文件。

如果有人可以查看错误并查看代码,如果某些内容已关闭,请告诉我。与此同时,我将继续自己做更多的研究。

我将从控制台的错误开始:

(main)2013-07-30 13:33:56,336 INFO [org.hibernate.impl.SessionFactoryImpl] - <closing>
(main)2013-07-30 13:33:56,336 ERROR [org.springframework.test.context.TestContextManager] - <Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@6c07588c] to prepare test instance [com.tom.rest.controller.invoice.InvoiceControllerTests@564686bc]>
(main)java.lang.IllegalStateException: Failed to load ApplicationContext
at  org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
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:321)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
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:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
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 'invoiceControllerTests': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.web.context.WebApplicationContext com.tom.rest.controller.invoice.InvoiceControllerTests.wac; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.web.context.WebApplicationContext] 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:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1120)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:103)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
at org.springframework.test.context.support.DelegatingSmartContextLoader.loadContext(DelegatingSmartContextLoader.java:228)
at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:124)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148)
... 24 more
 Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.web.context.WebApplicationContext com.tom.rest.controller.invoice.InvoiceControllerTests.wac; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.web.context.WebApplicationContext] 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$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 39 more
 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.web.context.WebApplicationContext] 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:949)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:818)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 41 more

applicationContext.xml由于依赖于dao和服务jar,这些导入来自该项目。

<import resource="classpath:project-dao.xml"/> 
<import resource="classpath:project-engines.xml"/> 
<import resource="classpath:project-infrastructure.xml"/> 
<import resource="classpath:project-interface.xml"/> 
<import resource="classpath:project-service.xml"/> 
<import resource="classpath:project-transactions.xml"/> 
<import resource="classpath:project-ui.xml"/> 
<import resource="classpath:project-webservices.xml" />

<context:component-scan base-package="com.tom.viper" />
<context:annotation-config />

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>

<bean id="invoiceControllerTests" class="com.tom.rest.controller.invoice.InvoiceControllerTests" />

用SpringMVC-servlet.xml中

<beans>
   <context:component-scan base-package="com.tom.viper, com.tom.cobra" />

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
          <property name="objectMapper">
             <bean class="com.fasterxml.jackson.databind.ObjectMapper">

                     <property name="dateFormat">
                        <bean class="java.text.SimpleDateFormat">
                            <constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg>
                        </bean>
                     </property>
             </bean>
          </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json"/>
</bean>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="messageConverters">
      <list>
        <ref bean="jsonHttpMessageConverter" />
      </list>
  </property>
</bean>

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <property name="messageConverters">
        <list>
        <ref bean="jsonHttpMessageConverter" />
        </list>
    </property>
</bean>
</beans>

的web.xml

<web-app>
     <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:/log4j.properties</param-value>
</context-param>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    /WEB-INF/classes/applicationContext.xml
    /WEB-INF/classes/springmvc-servlet.xml
    classpath:project-dao.xml
    classpath:project-engines.xml
    classpath:project-infrastructure.xml
    classpath:project-interface.xml
    classpath:project-service.xml
    classpath:project-transactions.xml
    classpath:project-ui.xml
    classpath:project-webservices.xml
    </param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Servlets -->
<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet>
    <servlet-name>jUnitHostImpl</servlet-name>
    <servlet-class>com.google.gwt.junit.server.JUnitHostImpl</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>jUnitHostImpl</servlet-name>
    <url-pattern>/RevenueManager/junithost/*</url-pattern>
</servlet-mapping>

<!-- Servlets -->

<!-- Default page to serve -->
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

现在控制器测试:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations =
{
"/applicationContext.xml",
"/springmvc-servlet.xml",
"classpath:project-infrastructure.xml",
"classpath:project-dao.xml",
"classpath:project-service.xml" })
public class InvoiceControllerTests
{
@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setup()
{
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}

@Test
public void getInvoices()
{
    assertEquals(true, true);
}
}

3 个答案:

答案 0 :(得分:0)

删除

<bean id="invoiceControllerTests" class="com.tom.rest.controller.invoice.InvoiceControllerTests" />

在applicationContext.xml中。

答案 1 :(得分:0)

您可以使InvoiceControllerTest实现ApplicationContextAware并从生命周期方法的实现中获取applicationContext的实例。
 或者,您可以在您的测试类中自动装配您想要测试的特定控制器实例,并执行这样的独立设置,
this.mockMvc = MockMvcBuilders.standaloneSetup(this.invoiceController).build();

答案 2 :(得分:0)

我来到一家新公司,该公司已经创建了一个Spring DAO和Services层,并进行了全面的单元测试。他们使用Ivy来处理依赖项和Ant build.xml文件来处理构建。我假设在创建JAR时,这将是一个包含所有配置文件和必要jar文件的自包含文件(封装)。当我破解打开JAR文件时,我感到震惊的是没有配置文件或jar,它只是项目本身的Java代码。这就是没有Spring配置文件的原因。

在我的新maven项目中,它问我上一个项目中缺少的所有罐子,所以我决定创建一个新的Maven Spring DAO / Service项目并将所有代码都带过来。

所以要更新:
在这个DAO和服务的新Maven项目中,我有Spring配置文件;的src /主/资源/弹簧 当这个新的JAR编译时,新的spring配置文件位于: WEB-INF /类/弹簧

所以,在我的Spring Web MVC项目中,现在是我的applicationContext.xml:

    <import resource="classpath*:projct-dao.xml"/> 
<import resource="classpath*:projct-engines.xml"/> 
<import resource="classpath*:project-infrastructure.xml"/> 
<import resource="classpath*:project-interface.xml"/> 
<import resource="classpath*:projct-service.xml"/> 
<import resource="classpath*:projct-transactions.xml"/> 
<import resource="classpath*:project-ui.xml"/> 
<import resource="classpath*project-webservices.xml" />

,这是处理spring上下文文件的web.xml的一部分:

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    /WEB-INF/classes/applicationContext.xml
    /WEB-INF/viper-servlet.xml
    classpath*:project-dao.xml
    classpath*:project-engines.xml
    classpath*:project-infrastructure.xml
    classpath*:poject-interface.xml
    classpath*:project-service.xml
    classpath*:project-transactions.xml
    classpath*:projct-ui.xml
    classpath*:project-webservices.xml
    </param-value>
</context-param>

将通配符(*)添加到类路径的末尾使它找到丢失的spring上下文文件。这解决了我的网络应用程序启动的问题...我希望这有助于其他人。