Wednesday, 28 June 2017

EasyMock, PowerMock: Accept any argument of given type to static method

In my previous post, I explained how to pass any object as an argument to mocked static method.  In this post, I am going to explain how to tell the mocked method accept any argument of given type.

EasyMock class provide 'isA()' by using this we can tell the mocked method to accept any object of this type as argument.

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

PowerMock.mockStaticPartial(StringUtil.class, "toUpper");
EasyMock.expect(StringUtil.toUpper(EasyMock.isA(String.class))).andReturn("HELLO PTR").times(1);
PowerMock.replayAll();
String result = StringUtil.toUpperAndRepeatStringTwice("hello ptr");

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

 public static 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() {
  PowerMock.mockStaticPartial(StringUtil.class, "toUpper");

  EasyMock.expect(StringUtil.toUpper(EasyMock.isA(String.class))).andReturn("HELLO PTR").times(1);

  PowerMock.replayAll();
  
  String result = StringUtil.toUpperAndRepeatStringTwice("hello ptr");

  assertEquals(result, "HELLO PTRHELLO PTR");

  PowerMock.verifyAll();
 }
}







Previous                                                 Next                                                 Home

No comments:

Post a Comment