skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Thursday, October 18, 2012

Using PowerMockito in JUnit

Posted by Raju Gupta at 4:00 AM – 0 comments
 
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.
Labels: jUnit Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger