In
this post, I am going to explain how to pass any object as an argument to
mocked static 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'.
PowerMock.mockStaticPartial(StringUtil.class,
"toUpper");
EasyMock.expect(StringUtil.toUpper(EasyMock.anyObject())).andReturn("HELLO
PTR").times(1);
PowerMock.replayAll();
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 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.anyObject())).andReturn("HELLO PTR").times(1); PowerMock.replayAll(); String result = StringUtil.toUpperAndRepeatStringTwice("hello ptr"); assertEquals(result, "HELLO PTRHELLO PTR"); PowerMock.verifyAll(); } }
No comments:
Post a Comment