Partial Mock Private Method with PowerMock-Mockito

I am new to Mockito and PowerMock. I need to test some legacy code which has a private method I have to mock. I am considering using the private partial mocking feature from PowerMock, I tried to mimic the example from the link, but it failed. I have no idea what's wrong with it. Could you help to check it? Thanks

Here's the class to-be-tested:

package test;
public class ClassWithPrivate
{ private String getPrivateString() { return "PrivateString"; } private String getPrivateStringWithArg(String s) { return "PrivateStringWithArg"; } }

And This is the Test Code:

package test;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.api.support.membermodification.MemberMatcher;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithPrivate.class)
public class ClassWithPrivateTest { @Test public void testGetPrivateString() { ClassWithPrivate spy = PowerMockito.spy(new ClassWithPrivate()); PowerMockito.doReturn("Do").when(spy, method(ClassWithPrivate.class, "getPrivateStringWithArg", String.class)).withArguments(anyString()); }
}

EDITWhen I tried to compile the code, it failed with the following errors:

ClassWithPrivateTest.java:26: unreported exception java.lang.Exception; must be caught or declared to be thrown PowerMockito.doReturn("Do").when(spy, method(ClassWithPrivate.class, "getPrivateStringWithArg", String.class)).withArguments(anyString()); ^
ClassWithPrivateTest.java:26: unreported exception java.lang.Exception; must be caught or declared to be thrown PowerMockito.doReturn("Do").when(spy, method(ClassWithPrivate.class, "getPrivateStringWithArg", String.class)).withArguments(anyString());
2

1 Answer

I found out the problem, the test methods expects a exception. After I modified it as follows, it is working fine.

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithPrivate.class)
public class ClassWithPrivateTest { @Test public void testGetPrivateString() throws Exception { ClassWithPrivate spy = PowerMockito.spy(new ClassWithPrivate()); PowerMockito.doReturn("Do").when(spy, method(ClassWithPrivate.class, "getPrivateStringWithArg", String.class)).withArguments(anyString()); }
}

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like