Mock private method using PowerMockito

You just need to change the mock method call to use doReturn. Example Partial Mocking of Private Method Test code @RunWith(PowerMockRunner.class) @PrepareForTest(MyClient.class) public class MyClientTest { @Test(expected = RuntimeException.class) public void testPublicAPI() throws Exception { MyClient classUnderTest = PowerMockito.spy(new MyClient()); // Change to this PowerMockito.doReturn(20).when(classUnderTest, “privateApi”, anyString(), anyInt()); classUnderTest.publicApi(); } } Console trace In publicApi … Read more

Using PowerMockito.whenNew() is not getting mocked and original method is called

You need to put the class where the constructor is called into the @PrepareForTest annotation instead of the class which is being constructed – see Mock construction of new objects. In your case: ✗ @PrepareForTest(MyQueryClass.class) ✓ @PrepareForTest(A.class) More general: ✗ @PrepareForTest(NewInstanceClass.class) ✓ @PrepareForTest(ClassThatCreatesTheNewInstance.class)

Mock a constructor with parameter

The code you posted works for me with the latest version of Mockito and Powermockito. Maybe you haven’t prepared A? Try this: A.java public class A { private final String test; public A(String test) { this.test = test; } public String check() { return “checked ” + this.test; } } MockA.java import static org.hamcrest.MatcherAssert.assertThat; import … Read more

How to mock private method for testing using PowerMock?

I don’t see a problem here. With the following code using the Mockito API, I managed to do just that : public class CodeWithPrivateMethod { public void meaningfulPublicApi() { if (doTheGamble(“Whatever”, 1 << 3)) { throw new RuntimeException(“boom”); } } private boolean doTheGamble(String whatever, int binary) { Random random = new Random(System.nanoTime()); boolean gamble = … Read more