How to inject a Mock in a Spring Context
This question already has an answer here:
Yes, you are on the right track, putting a mock @Bean
in a @Configuration
class is one approach, and I'll describe my experience:
The trick is that you need to use a different set of .xml files purely for testing which exclude the live versions of those beans.
@ContextConfiguration(locations = {"context1-test.xml", "context2-test.xml", ...})
And the "-test-xml" files go in src/test/resources
.
At least that was my experience in doing the same thing. Maybe there is some way to "override" the beans with the mock versions, but as yet I am not aware of it.
I also chose to put the mocks (I had 5 of them) all together in an own configuration:
@Configuration
public class MockServicesProvider {
@Bean
public AnotherBean myMock() { return mock(AnotherBean.class); }
}
Another interesting part of this problem is the common usage of initMocks(this);
in the @Before
method of your test class.
If the mocks are being used in other places (and they are, that's why you are wiring them up...) then initMocks(this)
will blow them away between tests (not literally - just that new mocks will be created and any other mocks wired up in other objects will be "lost").
The solution to this was to call mockito's reset(mockObject)
in the @Before
method before each test. The same mocks are reset (all the when
's and interactions), without creating new mocks.
Note that the Mockito docs for reset
say very sternly that this method should not commonly be used, except in the context of mocks being applied via dependency injection, as we are indeed doing in this case :)
Have fun!
It is indeed a duplicate of
Injecting Mockito mocks into a Spring bean
The Springockito-annotation is exactly what I was looking for
https://bitbucket.org/kubek2k/springockito/wiki/springockito-annotations
链接地址: http://www.djcxy.com/p/14394.html上一篇: 动态创建对象的依赖注入的好处
下一篇: 如何在Spring上下文中注入模拟