I am trying to Mock a class which has a nested class. That nested class was with a constructor argument. When I am trying to test using mockito instead of mocking the actual method is getting executed.
I have done @InjectMocks on outer class and @Mock of the inner class.
//Actual Class to test using Mockito.
public class ClassA {
public void initMethod(String s1, String s2, String s3, String s4) throws Exception {
ClassB objB = null;
if (objB == null && s3 != null && s4 != null && s2 != null) {
SampleUtil.KeyStorePasswordPair pair = SampleUtil.getKeyStorePasswordPair(s3, s4);
objB = new ClassB(s1, s2, pair.keyStore, pair.keyPassword);
try {
objB.meth1(); //Note: meth1 and meth2 are void methods.
objB.meth2(); // These two methods only to be accessed. something like doNothing
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Which I have tried as usual to call the class using @Mock but the actual method meth1() is getting accessed.
//Somthing which I tried
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
@InjectMocks
ClassA classA;
@Mock
ClassB classB;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testInitClient() throws Exception {
// Setup
// Run the test
classA.initMethod("Lorem", "Ipsum", "TestStr1", "TestStr2");
doNothing().when(classB).meth1(); // This is the line need to be mocked. But instead calling the actual method and executing
// Verify the results
}
The inner ClassB method needs to be mocked instead of accessing the real method.
As a beginner to mockito I am trying to clear this. But got confused on few points like accessing void method, SO can't use when then. Accessing constructor with parameter etc.,