Searching...
Sunday, 20 October 2013

How to Mock Static Methods using PowerMockito

08:18

PowerMockito extends Mockito functionality with several new features such as mocking static and private methods. In this example we will see how to mock static methods using PowerMockito. PowerMockito provides PowerMockito.mockStatic(..) method to create Mock object for Static methods and Mockito.when(….) we can set the method call and expected values.

Let us consider below scenario using a static method which requires mocking to test getEmployee method.

EmployeeDetails.java

public class EmployeeDetails {
	public Employee getEmployee(String empName) {
		return EmployeeProvider.getEmployee(empName);
	}
	
}

EmployeeProvider.java

package com.pretech;
public class EmployeeProvider {
	public static Employee getEmployee(String empName) {
		Employee emp = new Employee();
		return emp;
	}
}

Employee.java

public class Employee {
	private String empName;
	private String empAddress;
	//Getters and setters
}

EmployeeDetailsTest.java

import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.legacy.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({EmployeeProvider.class})
public class EmployeeDetailsTest {
	@Mock
	Employee emp;
	@Test
	public void testgetEmployee() throws Exception {
	Mockito.when(emp.getEmpName()).thenReturn("Vinod");
	Mockito.when(emp.getEmpAddress()).thenReturn("Bangalore");
        PowerMockito.mockStatic(EmployeeProvider.class);
        Mockito.when(EmployeeProvider.getEmployee("Vinod")).thenReturn(emp);
        EmployeeDetails empDetails=new EmployeeDetails();
        Assert.assertEquals("Bangalore",empDetails.getEmployee("Vinod").getEmpAddress());
	}
	
}


Notes
PowerMock requires below annotations inside test classes

@RunWith(PowerMockRunner.class)
@PrepareForTest({EmployeeProvider.class})


Output



image


Dependencies used in this example.

<properties>
    <powermock.version>1.5.1</powermock.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4-legacy</artifactId>
        <version>${powermock.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito</artifactId>
        <version>${powermock.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-easymock</artifactId>
        <version>1.5.1</version>
    </dependency>
</dependencies>

0 comments: