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() { ListattendanceBreakWSList = 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.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Shakil Pathan
Shakil is an experienced Groovy and Grails developer . He has also worked extensively on developing STB applications using NetGem .