【问题标题】:Issue with testing a Spring app with JUnit: NoSuchBeanDefinitionException raised only in tests使用 JUnit 测试 Spring 应用程序的问题:NoSuchBeanDefinitionException 仅在测试中引发
【发布时间】:2012-11-23 02:55:51
【问题描述】:

我在尝试使用 Spring 运行 JUnit 测试时遇到了严重问题。

这是我的 JUnit 类配置:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/META-INF/spring/applicationContext*.xml", "file:src/main/webapp/WEB-INF/spring/webmvc-config.xml" })

applicationContext*.xml 文件之一中,我确实有这个:

<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <beans:property name="basenames">
            <beans:list>
                <beans:value>messagesSecurity</beans:value>
            </beans:list>
        </beans:property>
    </beans:bean>

请注意,当我从 tomcat 运行我的应用程序时,它运行良好。 只有当我运行 JUnit 测试时,我才会收到以下 NoSuchBeanDefinitionException

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.context.support.ResourceBundleMessageSource] 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:924)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
    ... 118 more

我对这种行为感到很困惑...有人可以建议吗?

【问题讨论】:

    标签: spring unit-testing junit integration-testing


    【解决方案1】:

    我终于找到了问题的原因:我使用消息源 class 而不是使用导致代理问题的 interface

    重构我的应用程序以使用MessageSource 接口解决了问题。

    在 Spring 论坛上查看完整对话 here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 2023-03-21
      • 2023-03-07
      相关资源
      最近更新 更多