How to override the behavior of Spring @Autowired

后端 未结 3 1162
北荒
北荒 2020-12-19 05:06

A little background:

I am Using Spring 2.5, and specifically Spring IOC and annotations.

I am using @Autowired in my code (the Autowiring is don

相关标签:
3条回答
  • 2020-12-19 05:42

    I know this question is quite old but a I think an answer might still be useful for others.

    Since you probably do not want to mix both Foo and MockFoo within your context, I would suggest to remove Foo from the component-scanning. This could be done for example by specifying include/exclude filters on the <context:component-scan>.

    However if you are implementing unit tests, I would rather suggest not using a Spring context and just implementing "pure" unit tests by injecting mock-ups of the dependencies manually, so that you are only testing a single class. This can be achieved more easily by using a mocking framework like Mockito.

    0 讨论(0)
  • 2020-12-19 05:42

    I agree with Didier. Here is an example of how you can exclude the implementations that you want to mock in your test application context.

    <context:component-scan base-package="com.company" >
        <context:exclude-filter type="regex" expression="com\.abc\.service\.XDaoImpl"/>    
    </context:component-scan>
    

    Include this application context in your test as follows :

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={"classpath:/applicationContext-test.xml"})
    public class MyTest {....}
    
    0 讨论(0)
  • 2020-12-19 05:58

    Use ReflectionTestUtils to manually set the Mock in place of the autowired dependency (for that purpose your mock must not be spring managed, so that no ambiguity exists)

    0 讨论(0)
提交回复
热议问题