Wednesday, 18 March 2015

Mocking with Powermock

While I was discovering various features of Mocking, I came across two terms Mocks & Stubs, literal meaning of both these terms may seems synonumoys, but there is a fine line that separates them, Here is the difference

Mocks Vs Stubs:

I believe the biggest distinction is that a stub is already written with predetermined behavior. So we would have a class that implements the dependency (abstract class or interface most likely) we are faking for testing purposes and the methods would just be stubbed out with set responses. They wouldn't do anything fancy and we would have already written the stubbed code for it outside of your test. A mock is something that as part of our test we have to setup with your expectations. A mock is not setup in a predetermined way so you have code that does it in your test. Mocks in a way are determined at runtime since the code that sets the expectations has to run before they do anything. Tests written with mocks usually follow an initialize -> set expectations -> exercise -> verify pattern to testing. While the pre-written stub would follow an initialize -> exercise -> verify . The purpose of both is to eliminate testing all the dependencies of a class or function so our tests are more focused and simpler in what they are trying to prove. In order to mock behaviour, there are a number of tools available, they are Mockito, EasyMock, PowerMock etc. & there exists a fair and lot of resources on the cloud for each of them to learn about, but the thing that separates PowerMock from other is its ability to mock final classes. Here I am going to share a few scenarious of Mocking with PowerMock.

All the scenarios are described in the code itself with comments, so it becomes easy for us to co-relate. To describe the above scenarios, we would be referencing two helper classes, they are:
    1) Helper.java

    2) Entity.java

import java.sql.Date;

public class Entity {

 Date benefitDate;

 public Date getBenefitDate() {
  return benefitDate;
 }

 public void setBenefitDate(Date benefitDate) {
  this.benefitDate = benefitDate;
 }

 @Override
 public String toString() {
  return "Entity [benefitDate=" + benefitDate + "]";
 } 
}

&

public final class Helper {

 private  String formatDateTest(String str)
 {
  return new SimpleDateFormat("yyyy-MM-dd").format(new Date() );
 }
 
 /*public static String dataMethod() throws ParseException
 {
  return formatDate(null);
 }*/
 
 public  String invokePrivate(String data)
 {
  return this.formatDateTest(data);
 }
 
 private static String formatDate(java.util.Date d) throws ParseException
 {
  System.out.println(" The date in formatDate is:"+d.toString());
  
  SimpleDateFormat fromFormat = new SimpleDateFormat("yyyy-MM-dd");
  SimpleDateFormat toFormat = new SimpleDateFormat("MM/dd/yyyy");
  
  String d1 = toFormat.format(fromFormat.parse(d.toString()));
  return d1;
 }
 
 public static String writeEntityRecord(Entity entity) throws ParseException
 {
  String str = formatDate(entity.getBenefitDate());
  return str;
 }
 
 
 private static  String formatDateTestStatic(String str)
 {
  return new SimpleDateFormat("yyyy-MM-dd").format(new Date() );
 }

 public static String invokePrivateStatic(String data)
 {
  return formatDateTestStatic(data);
 }
 
 //Tested 
 public static String nonVoidPublicStaticMethod(Entity entity,StringBuilder stringBuilder)
 {
  return entity.toString()+stringBuilder.toString();
 }
 
 //Tested
 private static String nonVoidPrivateStaticMethod(Entity entity,StringBuilder stringBuilder)
 {
  return entity.toString()+stringBuilder.toString();
 }
 
 
 public  String nonVoidPublicMethod(Entity entity,StringBuilder stringBuilder)
 {
  return entity.toString()+stringBuilder.toString();
 }
 
 //Tested
 private  String nonVoidPrivateMethod(Entity entity,StringBuilder stringBuilder)
 {
  return entity.toString()+stringBuilder.toString();
 }
 
 
 
 public String callNonVoidPrivateStaticMethod(Entity entity,StringBuilder stringBuilder)
 {
  return nonVoidPrivateStaticMethod( entity, stringBuilder);
 }
 
 public static String callNonVoidPrivateStaticMethodWithStatic(Entity entity,StringBuilder stringBuilder)
 {
  return nonVoidPrivateStaticMethod( entity, stringBuilder);
 }
 
 public String callNonVoidPrivateMethod(Entity entity,StringBuilder stringBuilder)
 {
  return nonVoidPrivateMethod( entity, stringBuilder);
 }
}

The class where all the test scenarios are described is MockClass.java

@RunWith(PowerMockRunner.class)
@PrepareForTest({Helper.class,ExternalHelper.class})
public class MockClass  {
 
 Entity entity;
 StringBuilder  stringBuilder;

 @Before
 public void init()
 {
  entity = new Entity();
  entity.setBenefitDate(new Date(new java.util.Date().getTime()));
  stringBuilder = new StringBuilder();
 }
 ..............
 ................
 .....................

For using Powermock, we need to annotate the test class with PowerMockRunner.class and the classes to be mocked should be specified in @PrepareForTest annotation. The @PrepareForTest annotation can be specified at both class and method level. This annotation should include classes whose bytecode needed to be transformed i.e.final classes, classes with final, private, static or native methods that should be mocked and also classes that should be return a mock object upon instantiation. Since a Test class cannot have more than One Runner, situations when a Test Class needs to be annotated with a different runner and the Test Cases should also include mocking then we could use public @Rule PowerMockRule rule = new PowerMockRule() instead of PowerMockRunner and use the required Runner in its place. No Lets get into the scenarios one by one.

NEXT

View Subhankar Paul's profile on LinkedIn

No comments:

Post a Comment