Mock static method of a class in java in junit test cases.

Posted By : Shakil Pathan | 29-Sep-2017

Hi Guys,

In this blog, I am going to explain you about how to mock a static method of a class which we are using in the test class for which we are writing the test case.

For this purpose, I am using PowerMockito framework. PowerMockito is a PowerMock’s extension API which supports Mockito. PowerMockito provides capabilities to overcome the problems of Mockito, such as the lack of ability to mock static, final or private methods.

Below is a simple example to use PowerMockito in junit test case:

@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "org.springframework.security.core.context.SecurityContextHolder")
public class AttendanceBreakWebServiceImplTest {

	private AttendanceBreakWebServiceImpl attendanceBreakWebServiceImpl;
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}
	@Before
	public void setUp() throws Exception {
		attendanceBreakWebServiceImpl = new AttendanceBreakWebServiceImpl();
		mockStatic(SecurityContextHolder.class);
		when(SecurityContextHolder.getContext()).thenReturn(securityContext);
	}
	@After
	public void tearDown() throws Exception {
	}
	@Test
	public void testGetAttendanceBreaks() {
		List attendanceBreakWSList = attendanceBreakWebServiceImpl.getAttendanceBreaks("09/27/2017",
				"10/27/2017");
		assertTrue("attendanceBreakWSList is not empty", attendanceBreakWSList.isEmpty());
	}
}

In the above code we just have to run with "PowerMockRunner.class" and add "@PrepareForTest" for the class name for which you want to mock static method.

Without these two above annotations the test will fail. Please note that you can mock static methods in a class even though the class is final. The method can also be final.

Hope it help in writing junit test cases.

About Author

Author Image
Shakil Pathan

Shakil is an experienced Groovy and Grails developer . He has also worked extensively on developing STB applications using NetGem .

Request for Proposal

Name is required

Comment is required

Sending message..