Contains all information required to use PowerMochito to mock classes in JUnit
Jars:
mockito-all-<version>.jar
import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations. PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; Annotations: @RunWith(PowerMockRunner.class) @PrepareForTest( {Road.class, Car.class}) Mocking static methods: PowerMockito.mockStatic(Car.class); when(Car.getModel(any(Maruti.class), anyString())).thenReturn("Swift"); Mocking non-static methods: Road firstRoad = PowerMockito.mock(Road.class); when(firstRoad.getShortestRoute(any(Date.class))) .thenReturn(new Route(eastern)); Mocking exceptions: when(firstRoad.getShortestRoute(any(Date.class))).thenThrow(new IllegalArgumentException("test")); Mocking constructors: whenNew(Car.class).withParameterTypes(String.class).withArguments(anyString());
Note:
When passing arguments to the method you are mocking, do not try to mix matchers and actual arguments. It is safe to use matchers for all arguments because it is the return object that should matter. In case you want to specifically test something that you want to pass as an argument, it is better to do it in the form of assert statements.