I have the following use case:
I have a Test class with 3 components, from which 2 of them are inject into the third; I am using JUnit and Mockito for testing
public class MyTestClass{
@Mock
SomeService someService;
@Mock
AnotherService anotherService;
@InjectMock
MainService mainService;
@BeforeMethod
public void init() {
initMocks(this);
}
@Test
public void test(){
when(someService.someMethod(any())).thenReturn(something);
when(anotherService.someMethod(any()).thenReturn(something);
mainService.someMainMerhod();
// ...other assert logic
}
}
And here I have the MainService Spring component which has injected the two other components
@Component
public class MainService{
@Autowired
private SomeService someService; //Why here I have null component
private AnotherService anotherService; // and here I have an initialized component ???
public MainService(AnotherService anotherService){
this.anotherService = anotherService;
}
// implementation
}
Question 1 : Why someService instance is null when I am using both constructor and @Autowired?
Question 2 : Why if I am using only the constructor without @Autowired and vice versa, everything works, since I do not load the Spring context... I have unit tests...
The Javadoc states: "Mockito will try to inject mocks only either by constructor injection, setter injection, or property injection in order. If any of the strategy fail, then Mockito won’t report failure; i.e. you will have to provide dependencies yourself."
Hence it will fail silently.