Depencencies
- 'org.powermock:powermock-api-easymock:1.5.1'
- 'org.powermock:powermock-module-junit4:1.5.1'
- 'org.easymock:easymock:3.1'
PowerMockDemo
public class PowerMockDemo {
public void someMethod(String someArgument){
ClassA a = new ClassA();
ClassB b = new ClassB();
ClassC c = new ClassC();
c.setFirst(a);
c.setSecond(b);
c.execute(someArgument);
}
}
PowerMockDemoTest
Below is the unit test to test the PowerMockDemo.java.
import static org.powermock.api.easymock.PowerMock.*;
import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(PowerMockDemo.class)
public class PowerMockDemoTest {
private PowerMockDemo toTest;
@Test
public void testExcuteMethod() throws Exception {
toTest = new PowerMockDemo();
ClassA mockA = createMock(ClassA.class);
expectNew(ClassA.class).andReturn(mockA);
ClassB mockB = createMock(ClassB.class);
expectNew(ClassB.class).andReturn(mockB);
ClassC mockC = createStrictMock(ClassC.class);
expectNew(ClassC.class).andReturn(mockC);
mockC.setFirst(mockA);
expectLastCall().once();
mockC.setSecond(mockB);
expectLastCall().once();
mockC.execute(EasyMock.anyObject(String.class));
expectLastCall().once();
replayAll();
// run the test code
toTest.someMethod("Hello PowerMock");
verifyAll();
}
}
In the unit test above we asserted several things when the
PowerMockDemo#someMethod(String) is invoked.
PowerMock.createMock() - is used to instantiate a new mock object.
PowerMock.expectNew() - is used to specify that a new a new instance is expected and when it is invoked the specified mock object is returned.
PowerMock.createStrictMock() - is also used to create a new mock object. The only difference is that, when compared to createMock(), the order of method invocations on the mock object is asserted.
References: