I'm trying to inject a child mock to my Main.class, and it doesn't seem to work. (Using powermock 1.7.0 with junit bundled with dependencies)
The verification says that my mocked object was not interacted. can't figure out why.
This is my Main.class:
public class Main {
private Child child;
public Main(){ }
public void setChild(Child child){
this.child = child;
}
public void play(){
child = new Child();
child.setNumber(50);
System.out.println(child.getNumber());
}
}
This is my Child.class :
public class Child {
private int number;
public void setNumber(int number){
this.number = number;
}
public int getNumber(){
return number;
}
}
And this is my Test.class:
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Child.class, Main.class})
public class MainTest {
private Child child;
private Main main;
@Test
public void testMain(){
main = new Main();
main.play();
Mockito.verify(child).getNumber();
}
@Before
public void setup(){
child = mock(Child.class);
when(child.getNumber()).thenReturn(10);
}
}
The mock you create in your test is never actually used, because the Main object creates a new Child object each time you call play() on it.
What you want is a way to tell the production code to use the mocked child instance, e.g. by means of a setter.
Main
public void play(){
// child = new Child(); // do not create a new instance each time
child.setNumber(50);
System.out.println(child.getNumber());
}
MainTest
@Test
public void testMain(){
main = new Main();
main.setChild(child); // tell it to use the mock
main.play();
Mockito.verify(child).getNumber();
}