Issue
I have a code where @InjectMocks is not able to add second level mocked dependencies.
public class Token{
//setters getters and logic
}
public class TokenManager{
public Token getToken(){
//Some logic to return token
}
}
public class MyClass {
private TokenManager tmgr;
public MyClass(TokenManager tmgr){
this.tmgr = tmgr;
}
public void doLogic(){
Token token = tmgr.getToken();
String tokenStr = token.getString();
//Logic
}
}
@Run(MockitoJunit4)
public class MyClassTest{
@Mock
TokenManager tmgr;
@Mock
Token token;
@InjectMocks
MyClass myClass;
@Begin
public void setup(){
MockitoAnnotations.initMocks(this);
}
@Test
public void doLogicTest{
String sometestStr = "ABCD";
when(tmg.getToken()).thenReturn(token);
when(token.getString()).thenReturn(sometestSTR);
myClass.doLogic();
//some asserts
}
}
Code is returning NullPointer at
String tokenStr = token.getString()
I am not able to do Junit testing for because of this. If i add these mocked dependencies via constructor of MyClass, it works
Solution
Your example has some problems with annotations and mocking objects. Try to change code in the test class like that:
public class MyClassTest {
@Mock
TokenManager tmgr;
@InjectMocks
MyClass myClass;
@Before
public void setup(){
initMocks(this);
}
@Test
public void doLogicTest {
Token token = mock(Token.class);
String sometestStr = "ABCD";
when(tmg.getToken()).thenReturn(token);
when(token.getString()).thenReturn(sometestSTR);
myClass.doLogic();
//some asserts
}
}
Answered By - Dmitrii Bykov