Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.
Use the @PrepareForTest(ClassToPartiallyMock.class) annotation at the class-level of the test case.
se PowerMock.createPartialMock(ClassToPartiallyMock.class, "nameOfTheFirstMethodToMock", "nameOfTheSecondMethodToMock") to create a mock object that only mocks the methods with name nameOfTheFirstMethodToMock and nameOfTheSecondMethodToMock in this class (let's call it mockObject).
Use PowerMock.replay(mockObject) to change the mock object to replay mode.
Use PowerMock.verify(mockObject) to change the mock object to verify mode.
For those that are having problems with non-initialized fields: the PowerMock?.createPartialMock method doesn't invoke the constructor and doesn't initialize the fields. This can cause strange behavior when testing, and NullPointerExceptions?.
The solution is to use the method PowerMock?.createPartialMockAndInvokeDefaultConstructor instead.
You can use createPartialMock(Class<T> type, String methodNames, Object... constructorArguments) and createPartialMockAndInvokeDefaultConstructor. Please use the mailing-list for asking questions in the future.
For those that are having problems with non-initialized fields: the PowerMock?.createPartialMock method doesn't invoke the constructor and doesn't initialize the fields. This can cause strange behavior when testing, and NullPointerExceptions?.
The solution is to use the method PowerMock?.createPartialMockAndInvokeDefaultConstructor instead.
This was something I had problems with untill Johan Haleby helped me out in this forum discussion: http://groups.google.com/group/powermock/browse_thread/thread/b6634ccfcb581f2f
What if we want to invoke a constructor taking some parameter and also partially mock some methods.
You can use createPartialMock(Class<T> type, String methodNames, Object... constructorArguments) and createPartialMockAndInvokeDefaultConstructor. Please use the mailing-list for asking questions in the future.
What is the simplest way to partially mock a super-class method?
To my knowledge this is not possible in Java since that will break polymorphism.
Use mockStaticPartial method to mock partially a class with static methods. Example:
package mgmt.api;
class CustomerService? {
}package mgmt.api;
import static org.powermock.api.easymock.PowerMock?.expectLastCall; import static org.powermock.api.easymock.PowerMock?.mockStaticPartial; import static org.powermock.api.easymock.PowerMock?.replayAll;
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?(CustomerService?.class) public class CustomerServiceTest? {
}