Thursday, 22 June 2017

PowerMock, EasyMock: Mock static void private method

In this post, I am going to explain how to mock private static void methods. PowerMock provides 'expectPrivate' method to specify expectations on private methods using the method name.

Example
String message = "Enter Your Name";
String methodToMock = "readInputFromUI";
PowerMock.mockStaticPartial(InputUtil.class, methodToMock);
PowerMock.expectPrivate(InputUtil.class, methodToMock, message.toUpperCase()).times(5);

Above statement mock the private method 'readInputFromUI' and expect argument as "ENTER YOUR NAME" (in upper case).

Following is the complete working application.

InputUtil.java
package com.sample.tests;

import javax.swing.JOptionPane;

public class InputUtil {

 public static void readInput(String message){
  readInputFromUI(message.toUpperCase());
 }
 
 private static void readInputFromUI(String message){
  JOptionPane.showInputDialog(message);
 }
 
}


InputUtilTest.java
package com.sample.tests;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ InputUtil.class })
public class InputUtilTest {

 @Test
 public void mockVoidEvenMethod() throws Exception {
  String message = "Enter Your Name";
  String methodToMock = "readInputFromUI";

  PowerMock.mockStaticPartial(InputUtil.class, methodToMock);

  PowerMock.expectPrivate(InputUtil.class, methodToMock, message.toUpperCase()).times(5);

  PowerMock.replayAll();

  for (int i = 0; i < 5; i++) {
   InputUtil.readInput(message);
  }
  
  PowerMock.verifyAll();
  

 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment