Reputation: 330
I have the following class under test. I need to mock a method call- estabilishConnection from constructor, which returns void.
public class ClassToBeTested {
private ClassToBeMocked classToBeMocked;
private String name;
private int age;
ClassToBeTested(ClassToBeMocked classToBeMocked, String name){
this.classToBeMocked = classToBeMocked;
this.name = name;
age = this.getAge(name);
this.estabilishConnection();
}
private int getAge(String name){
int age = (int) classToBeMocked.getNameAgeMap().get(name);
return age;
}
private void estabilishConnection(){
``````````````````````````
````````````````````````
}
}
Below given is the method that I have tried. But it is not working
@Test
public void testMethodInClassToBeMocked(){
ClassToBeMocked mockApp = Mockito.mock(ClassToBeMocked.class);
HashMap testMap= new HashMap();
testMap.put("xys", 11);
Mockito.when(mockApp.getNameAgeMap()).thenReturn(testMap);
///PowerMockito for mocking the void method
PowerMockito.spy(ClassToBeTested.class);
PowerMockito.doNothing().when(ClassToBeTested.class, "estabilishConnection");
ClassToBeTested classTest = new ClassToBeTested(mockApp, "xys");
//Assertion of method in the test class goes here
}
How can I make the method estabiishConnection to do nothing?
Upvotes: 1
Views: 412
Reputation: 330
PowerMockito.stub(PowerMockito.method(ClassToBeTested.class, "estabilishConnection")).toReturn("nothing");
This one solved the issue
Upvotes: 1