Thursday 20 July 2017

Mock instance void private method

In this post, I am going to explain how to mock instance private void methods. PowerMock class provides 'expectPrivate' method, by using this we can mock private methods of an object. Following snippet mocks the private instance method 'sendStringToLogger'.

String methodToMock = "sendStringToLogger";
StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, methodToMock);
String input = "hello ptr";
PowerMock.expectPrivate(stringUtil, methodToMock, input).times(1);

Following is the complete working application.

MethodNotImplementedException.java
package com.sample.model;

public class MethodNotImplementedException extends RuntimeException {
 private static final long serialVersionUID = 1L;

 public MethodNotImplementedException() {
  super();
 }

 public MethodNotImplementedException(String message) {
  super(message);
 }

}

StringUtil.java
package com.sample.util;

import com.sample.model.MethodNotImplementedException;

public class StringUtil {
 public String toUpperAndRepeatStringTwice(String str) {
  String upperCase = str.toUpperCase();
  sendStringToLogger(str);
  return upperCase + upperCase;
 }
 
 private void sendStringToLogger(String str){
  throw new MethodNotImplementedException();
 }
}


StringUtilTest.java
package com.sample.util;

import static org.junit.Assert.assertEquals;

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({ StringUtil.class })
public class StringUtilTest {

 @Test
 public void toUpperAndRepeatStringTwice() throws Exception {
  String methodToMock = "sendStringToLogger";
  
  StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, methodToMock);

  String input = "hello ptr";

  PowerMock.expectPrivate(stringUtil, methodToMock, input).times(1);
  PowerMock.replayAll();

  String result = stringUtil.toUpperAndRepeatStringTwice(input);

  assertEquals(result, "HELLO PTRHELLO PTR");
  
  PowerMock.verifyAll();

 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment