In order to set arbitrary behavior with static method and private method in PowerMock, it is first necessary to mock / spy the target class.
Here, it is assumed that the Utility class will be mocked / spyed.
Utility.java
public class Utility {
//The contents are omitted. anything is fine.
}
Mocking in PowerMock, like Mockito, is used to arbitrarily define the behavior of a method for the convenience of unit tests. You can also record and verify the number of calls.
Immediately after mocking, the mock object is in a state where the behavior of the method is not defined, so use it by defining a return value or exception with doReturn or doThrow. (* Methods that do not define behavior return null as a return value.)
To mock, pass the Class of the class you want to mock to the argument of PowerMockito.mock.
Utility mock = PowerMockito.mock(Utility.class);
Unlike mocking, spying is used when you want to define arbitrary behavior for some methods.
Immediately after spying, the Utility class behaves just like an instance of a regular Utility class. (Recording and verification of the number of calls is possible.)
In other words, it works in the same way as a normal method, except for methods that set arbitrary behaviors and exceptions with doReturn, doThrow, etc.
To spy, pass an instance of the class you want to mock in the PowerMockito.spy argument.
Utility spy = PowerMockito.spy(new Utility());
Recommended Posts