Saturday, 15 July 2017

Mock instance void method

In this post, I am going to show how to mock instance void methods. Sometimes you don’t want to call void methods, while testing a function (which in turn calling this void method). By using ‘expectLastCall’ method of EasyMock class, you can mock instance void methods.

Following statements are used to mock the instance void method 'sendStringToLogger'.

StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, "sendStringToLogger");
stringUtil.sendStringToLogger();
PowerMock.expectLastCall().times(1);
PowerMock.replayAll();

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();
  return upperCase + upperCase;
 }
 
 public void sendStringToLogger(){
  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() {
  StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, "sendStringToLogger");

  stringUtil.sendStringToLogger();
  PowerMock.expectLastCall().times(1);
  
  PowerMock.replayAll();

  String result = stringUtil.toUpperAndRepeatStringTwice("hello ptr");

  assertEquals(result, "HELLO PTRHELLO PTR");

 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment