Monday 3 July 2017

PowerMock, EasyMock : Pass any object as an argument to instance method

In this post, I am going to explain how to pass any object as an argument to mocked instance method. EasyMock class provide 'anyObject()' by using this we can tell the mocked method to accept any object as argument.

Following snippet is used to mock the method 'toUpper' which accepts any argument and return 'HELLO PTR'.

StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, "toUpper");
EasyMock.expect(stringUtil.toUpper(EasyMock.anyObject())).andReturn("HELLO PTR").times(1);
EasyMock.replay(stringUtil);    
String result = stringUtil.toUpperAndRepeatStringTwice("hello ptr");

Find the following 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 toUpper(String str) {
  throw new MethodNotImplementedException();
 }

 public String toUpperAndRepeatStringTwice(String str) {
  String upperCase = toUpper(str);
  return upperCase + upperCase;
 }
}


StringUtilTest.java
package com.sample.util;

import static org.junit.Assert.assertEquals;

import org.easymock.EasyMock;
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, "toUpper");

  EasyMock.expect(stringUtil.toUpper(EasyMock.anyObject())).andReturn("HELLO PTR").times(1);

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

  assertEquals(result, "HELLO PTRHELLO PTR");

  PowerMock.verifyAll();
 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment