How can I mock private static method with PowerMockito?

后端 未结 3 1395
渐次进展
渐次进展 2020-12-08 15:07

I\'m trying to mock private static method anotherMethod(). See code below

public class Util {
    public static String method(){
        return          


        
相关标签:
3条回答
  • 2020-12-08 15:43

    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.

    0 讨论(0)
  • 2020-12-08 15:56

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

    PowerMockito.doReturn("abc").when(Util.class, "anotherMethod", parameter);
    
    0 讨论(0)
  • 2020-12-08 15:56

    I'm not sure what version of PowerMock you are using, but with the later version, you should be using @RunWith(PowerMockRunner.class) @PrepareForTest(Util.class)

    Saying this, I find using PowerMock to be really problematic and a sure sign of a poor design. If you have the time/opportunity to change the design, I would try and do that first.

    0 讨论(0)
提交回复
热议问题