Here's the problem: I have a rather complex class B with lots of @Inject
defined in it (among them a class C). An instance of this class is injected into another class A, which I want to be tested.
The idea is that I want to inject a mock of class B into A - and I want it to be injected by spring to have the init-method be executed after the instance is created (so no @InjectMock
here to have an alternative injection).
Here's an example that is boiled down to three classes Bla, Blub and Blublub. What I want to do is have a mock of Blub and inject this instance into BlubBlub - and I want to ignore the existence of Bla.
*Edited*
The main point is that I want a context to consists of a mock of class Blub and an instance of class BlubBlub.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MockInjectionTest.TestApp.class)
public class MockInjectionTest {
@Inject
public Blub blub;
@Inject
public BlubBlub blubblub;
@Configuration
public static class TestApp {
@Bean
Blub getBlub() {
return mock(Blub.class);
}
@Bean
BlubBlub getBlubBlub() {
return new BlubBlub();
}
}
@Test
public void testBlub() {
Assert.assertNotNull(blub);
}
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
// the classes
public static class Bla {
}
public static class Blub {
@Inject
public Bla bla;
}
private static class BlubBlub {
@Inject
public Blub blub;
}
}
Problem: when I define a mock of Blub either by using @Mock
or by calling mock(Blub) explicitly in a @Bean method I get the following error when the ApplicationContext
is instantiated (no matter whether I use xml-config or annotation-based bean definitions).
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'getBlub': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: public Bla Blub.bla;
so apparently Spring still want to instantiate the original class instead of just taking my provided instance. This seams to be necessary to create the context (if I create the context by hand and pull the bean with ctx.getBean()
it dumps already in the context construction).
Coming from Guice I would simple bind my mocked instance into the module and everything would be fine.
Help is much appreciated - sounds like a standard problem but I couldn't find a simple solution.
thanks and regards, fricke