Saturday, January 4, 2014

Invoke protected method with PowerMockito

My objective is to invoke the real execution of a method during the unit test. The hardest part on running this unit test is I'm targeting on a protected method. Mockito couldn’t do well with this, but PowerMockito do provide a very good solution on private/protected method. Following scenario shows how the existing classes were designed, and the target method that I’m going to unit test is initConnection().
public abstract class ReportService {

 ...

 protected void initConnection() {
  try {
   Class.forName("com.informix.jdbc.IfxDriver");
   
   session = HibernateUtil.currentSession();
   session.beginTransaction();
  } catch(Exception e) {
   e.printStackTrace();
  }
 }

 ...
}

public abstract class HibernateReportService<T> extends ReportService {

 ...

 public void execute() {
  
  try {
   initConnection();

   ...
   ...

}
To achieve my objective, there are 2 possible ways for the setup in my stub code. It is either Method 1:
 public void initConnectionCallRealMethod() throws Exception {
  PowerMockito
   .when(this.daoReportService, PowerMockito.method(ReportService.class, "initConnection"))
   .withNoArguments()
   .thenCallRealMethod();
 }
Or Method 2:
 public void initConnectionCallRealMethod() throws Exception {
  PowerMockito.doCallRealMethod()
   .when(this.daoReportService, PowerMockito.method(ReportService.class, "initConnection"))
   .withNoArguments();
 }
}
this.daoReportService is an instance of object that extends from HibernateReportService which is being spy. And also notice the use of PowerMockito.method(), this is due to the reason initConnection() is not visible to the outside world, thus the regular use of when() will not going to work.

No comments: