Monday 10 July 2017

Mocking: Accept any argument of given type to instance method

In my previous post, I explained how to pass any object as an argument to mocked instance 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'.

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

Find the following working application.

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.isA(String.class))).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