2

I defined a bean in spring context file 'applicationContext.xml' like below :

<bean id="daoBean" class="org.mockito.Mockito" factory-method="mock">
        <constructor-arg value="com.xxx.DAOImpl" />
</bean> 

In my service class (ServiceImpl), I am using this bean like below:

 @Component("serviceImpl")
 public class ServiceImpl{
        // other code here

        @Autowired
        private transient DAOImpl daoBean;

        // other code here
    }

My service class is being accessed from my JUnit test class.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext.xml" }) 
public class JUnitTest{
    // other code here

    @Autowired
    private transient ServiceImpl serviceImpl;

    // test cases are here
}

When I execute the test case, it gives error saying:

Error creating bean with name 'ServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private transient com.xxx.DAOImpl

When I remove @Autowired from service class and use @Resource(name = "daoBean") the test case works fine.

public class ServiceImpl{
            // other code here

            @Resource(name = "daoBean")
            private transient DAOImpl daoBean;

            // other code here
        }

My question is why @Autowired is not working in this case? Do I need to configure any thing else with @Autowired, so that it can work properly. I don't want to change my service layer classes to replace @Autowired to @Resource.

Jesse
  • 8,605
  • 7
  • 47
  • 57
Narendra Verma
  • 2,372
  • 6
  • 34
  • 61

1 Answers1

3

Mockito.mock() has a generic return type T which is erased at runtime, so Spring cannot infer the type of the created mock that will be simply registered as Object in the Spring context. That's why @Autowired doesn't work (as it tries to look up the dependency by its type).

Check out this answer for a solution to the problem.

Community
  • 1
  • 1
zagyi
  • 17,223
  • 4
  • 51
  • 48