2

Spring 3.2.3.Release 和 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 版本。

我花了 2 天时间在 Internet、Google 和 StackOverflow 以及 Spring 论坛上寻找明确的答案,但我无法得到我需要的确切答案,所以我需要另一双眼睛来查看我的文件看看是不是基本有问题。

问题是我的单元测试不起作用,它非常小,但出现了一个巨大的错误,我什至无法执行任何测试。所以,让我开始列出我的代码和 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 和 service 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);
}
}
4

3 回答 3

0

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

在我的新 maven 项目中,它要求我提供以前项目中缺少的所有 jar,所以我决定创建一个新的 Maven Spring DAO/Service 项目并将所有代码带过来。

所以要更新:
在这个用于 DAO 和服务的新 Maven 项目中,我在下面有 Spring 配置文件;src/main/resources/spring,当这个新的 JAR 编译时,新的 spring 配置文件位于:WEB-INF/classes/spring

所以,在我的 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" />

这是处理弹簧上下文文件的 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 上下文文件。这解决了我的网络应用程序启动的问题......我希望这对其他人有帮助。

于 2013-08-05T14:28:03.307 回答
0

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

于 2013-07-31T10:54:24.737 回答
0

消除

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

在您的 applicationContext.xml 中。

于 2013-07-31T01:01:44.133 回答