I have the below flow
@InjectMocks private ClassToTest classToTest;
@Mock private ClassToInject classToInject;
@Before
public void setup() {
initMocks(this);
}
@Test
public void test() {
Classx mockClassObj = Mockito.mock(Classx.class);
when(classToInject.publicMethod1(mockClassObj)).thenReturn(1000);
classToTest.publicMethod();
}
I want to test public method of classToTest. Now this method makes call to a private method, which I am not mocking. Inside this private method another public method is called, which I want to mock publicMethod1
. Instead of the private method making use of value 1000 it is behaving as if the publicMethod1
was not mocked and I get NPE inside the flow of the method somewhere. I tried using @Spy with classToTest
and also I am using init.mocks/@RunWith but it fails.
In short it is something like
ClassToTest. publicMethod --> ClassToTest.privateMethod(not mocking) --> ClassToInject.publicMethod1(want to mock)
The class looks like below
class ClassToTest {
@Inject ClassToInject classToInject;
public publicMethod() {
privateMethod();
}
private privateMethod() {
int x = classToInject.publicMethod1();
// use the return value
// throw exception
}