Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock private static method with PowerMockito?

Tags:

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?

like image 482
Aaron Avatar asked Aug 31 '14 16:08

Aaron


People also ask

Can we mock private static method?

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.

Can we mock static methods in Mockito?

Since static method belongs to the class, there is no way in Mockito to mock static methods.


2 Answers

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.

like image 116
troig Avatar answered Oct 15 '22 03:10

troig


If anotherMethod() takes any argument as anotherMethod(parameter), the correct invocation of the method will be:

PowerMockito.doReturn("abc").when(Util.class, "anotherMethod", parameter); 
like image 21
Umut Uzun Avatar answered Oct 15 '22 04:10

Umut Uzun