Monthly Archives: March 2014

Using PowerMock to mock a call to super

Let’s say you are wanting to test UberEmployee below:

[java]
public class Employee {
public int calculatePay() {
return someComplexCalculations;
}
}

public class UberEmployee {
public static final long UBER_BONUS = 1000;
@Override
public int calculatePay() {
return super.calculatePay() + 1000;
}
}
[/java]

Perhaps you can’t change Employee but you still want to test UberEmployee without your tests being unnecessarily coupled to the implementation of Employee. We can utilize PowerMock to mock the call to Employee.calculatePay(). It takes a little bit of voodoo but it can be done like this:

[java]
@RunWith(PowerMockRunner.class)
@PrepareForTest({Employee.class})
public class UberEmployeeTest {
private UberEmployee uberEmployee = new UberEmployee();

@Test
public void calculatePayShouldGiveUberBonus() {
final long pay = RandomUtils.nextLong();
Method superCalculatePayMethod = Employee.class.getMethod("calculatePay");
PowerMockito.replace(superCalculatePayMethod).with(new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return pay;
}
});

assertThat(uberEmployee.calculatePay(), is(pay + UberEmployee.UBER_BONUS));
}
}
[/java]

It’s not really pretty but it does the trick whenever you don’t have any other choice.