Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Mockito: Mock static methods


In this post, I am going to explain how to mock Static methods.

public class EmployeeService {

         public static List getEmployeeFirstNames(List employees){
                 throw new MethodNotImplementedException();
         }
}


As you see the above snippet, EmployeeService class has unimplemented method 'getEmployeeFirstNames'. If any methods that are using 'getEmployeeFirstNames' method in their implementation end up in 'MethodNotImplementedException'.

By using powermockito, we can mock and test Static Methods like below.

PowerMockito.mockStatic(EmployeeService.class);
Above statement mocks EmployeeService class.

PowerMockito.when(EmployeeService.getEmployeeFirstNames(employees)).thenReturn(employeeNames);
Above statement tells PowerMockito, return employeeNames, when getEmployeeFirstNames is called with employees.

Find the below working application.

MethodNotImplementedException.java
package com.sample.exceptions;

public class MethodNotImplementedException extends RuntimeException {
private static final long serialVersionUID = 1L;

public MethodNotImplementedException() {
super();
}

public MethodNotImplementedException(String message) {
super(message);
}

}



This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Mockito: Mock static methods

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×