【问题标题】:Spring Testing with JUnit4 Runner does not work after trying different solutions尝试不同的解决方案后,使用 JUnit4 Runner 进行 Spring 测试不起作用
【发布时间】:2018-11-16 15:34:02
【问题描述】:

当使用 JUnit4 Test Runner 自动装配我的 spring 测试类时,上下文启动会产生以下异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mypackage.TestClass': Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mypackage.ServiceClass com.mypackage.TestClass.service; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mypackage.ServiceClass] 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)}

我的设置

TestClass 注释如下

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/testContext.xml"})

自动装配的字段是这样注释的

 @Autowired
 ACrudRepository repository; // is autowired

 @Autowired
 @Qualifier("service")
 ServiceClass service; // is NOT autowired

testContext.xml 具有以下 Bean 定义(以及更多):

<bean class="com.mypackage.ServiceClass" id="service">
    <property name="someBoolean" value="false"/>
    <property name="otherBoolean" value="false"/>
    <property name="someList">
      <list><value>withOneValue</value></list>
    </property>
</bean>

<jpa:repositories base-package="com.mypackage"/>

我尝试过的:

【问题讨论】:

  • 尝试将autowire="byName" 添加到` `.along with @Qualifier("service") on your autowired bean
  • 不幸的是不能工作
  • 你的 testContext.xml 文件在哪里?
  • @NawnitSen 它位于test/resources/spring/testContext.xml 目录中。如问题中所述,找到了&lt;jpa:repositories base-package="com.mypackage"/&gt;,并注入了它的bean。因此testContext.xml 应该没问题
  • 你可以尝试使用java配置一次而不是使用xml文件吗?或者这可能有助于“github.com/sbrannen/spring-test-junit5/issues/6

标签: java junit4 spring-test


【解决方案1】:

这个项目中的问题(这里没有提到)是自动装配 bean 中的&lt;tx:annotation-driven/&gt; 标记和@Transactional 注释。这个注解通常使用不能自动装配的java interface-based-proxy,因为它们不是同一个类的类型。

为了解决这个问题,我们使用了标签&lt;tx:annotation-driven proxy-target-class="true"/&gt;

非常感谢这个答案:https://stackoverflow.com/a/19624412

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2011-03-22
    • 2023-03-15
    • 2013-03-27
    • 2022-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多