xetra11
xetra11

Reputation: 8885

Spring Testing with JUnit4 Runner does not work after trying different solutions

When autowiring my spring test class with the JUnit4 Test Runner the context startup yields the following exception:

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)}

My Setup

The TestClass is annotated as followed

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

The autowired fields are annotated like this

 @Autowired
 ACrudRepository repository; // is autowired

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

The testContext.xml has the following Bean definition (and some more):

<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"/>

What I have tried:

Upvotes: 1

Views: 140

Answers (1)

r-vanooyen
r-vanooyen

Reputation: 121

The problem in this projekt (which was not mentioned here) was the <tx:annotation-driven/> tag and @Transactional annotation in the autowired bean. This annotation usualy uses java interface-based-proxy which can not be autowired, because they are not of the same type of the class.

To Fix this we used the tag <tx:annotation-driven proxy-target-class="true"/>.

Much thanks to this answer: https://stackoverflow.com/a/19624412

Upvotes: 1

Related Questions