如何使用PowerMockito模拟私有静态方法?

2022-09-01 18:36:13

我试图嘲笑私有静态方法。请参阅下面的代码anotherMethod()

public class Util {
    public static String method(){
        return anotherMethod();
    }

    private static String anotherMethod() {
        throw new RuntimeException(); // logic was replaced with exception.
    }
}

这是我的测试代码

@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");
        }    
}

但是我运行它的每个磁贴我都会得到这个异常

java.lang.AssertionError: expected object to not be null

我想我在嘲笑东西方面做错了什么。任何想法我该如何解决它?


答案 1

为此,您可以使用 和 。PowerMockito.spy(...)PowerMockito.doReturn(...)

此外,您必须在测试类中指定 PowerMock 运行程序,并准备该类以进行测试,如下所示:

@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");
   }
}

希望它能帮助你。


答案 2

如果另一个Method()将任何参数作为另一个Method(参数),则该方法的正确调用将是:

PowerMockito.doReturn("abc").when(Util.class, "anotherMethod", parameter);

推荐