See Whitebox.setInternalState(...)
.
For example - given class A
which needs to be tested:
public class A {
private B b;
public A() {
b = new B();
}
public void doSomething() {
b.doSomething();
}
}
which has a private instance of B
:
public class B {
public void doSomething() {
// some long running, resource intensive process...
System.out.println("Real B.doSomething() was invoked.");
}
}
then Whitebox
can be used to set the private state of A
so it can be tested:
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.reflect.Whitebox;
@RunWith(MockitoJUnitRunner.class)
public class ATest {
@Mock
private B b;
private A a;
@Before
public void prepareTest() {
doNothing().when(b).doSomething();
a = new A();
Whitebox.setInternalState(a, B.class, b);
}
@Test
public void doSomething() {
a.doSomething();
verify(b).doSomething();
}
}