I'm trying to mock private static method anotherMethod()
. See code below
public class Util { public static String method(){ return anotherMethod(); } private static String anotherMethod() { throw new RuntimeException(); // logic was replaced with exception. } }
Here is me test code
@PrepareForTest(Util.class) public class UtilTest extends PowerMockTestCase { @Test public void should_prevent_invoking_of_private_method_but_return_result_of_it() throws Exception { PowerMockito.mockStatic(Util.class); PowerMockito.when(Util.class, "anotherMethod").thenReturn("abc"); String retrieved = Util.method(); assertNotNull(retrieved); assertEquals(retrieved, "abc"); } }
But every tile I run it I get this exception
java.lang.AssertionError: expected object to not be null
I suppose that I'm doing something wrong with mocking stuff. Any ideas how can I fix it?
For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.
Since static method belongs to the class, there is no way in Mockito to mock static methods.
To to this, you can use PowerMockito.spy(...)
and PowerMockito.doReturn(...)
.
Moreover, you have to specify the PowerMock runner at your test class, and prepare the class for testing, as follows:
@PrepareForTest(Util.class) @RunWith(PowerMockRunner.class) public class UtilTest { @Test public void testMethod() throws Exception { PowerMockito.spy(Util.class); PowerMockito.doReturn("abc").when(Util.class, "anotherMethod"); String retrieved = Util.method(); Assert.assertNotNull(retrieved); Assert.assertEquals(retrieved, "abc"); } }
Hope it helps you.
If anotherMethod() takes any argument as anotherMethod(parameter), the correct invocation of the method will be:
PowerMockito.doReturn("abc").when(Util.class, "anotherMethod", parameter);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With