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

时间:2014-08-31 16:42:42

标签: java unit-testing mockito

我试图模仿私有静态方法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

我认为我在做嘲弄事情时做错了。任何想法我该如何解决?

3 个答案:

答案 0 :(得分:33)

为此,您可以使用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");
   }
}

希望它对你有所帮助。

答案 1 :(得分:6)

如果anotherMethod()将任何参数作为anotherMethod(参数),则方法的正确调用将为:

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

答案 2 :(得分:-1)

我不确定您使用的是哪个版本的PowerMock,但是对于更高版本,您应该使用@RunWith(PowerMockRunner.class) @PrepareForTest(Util.class)

说到这一点,我发现使用PowerMock确实存在问题,并且确实表明设计不佳。如果你有时间/机会改变设计,我会先尝试这样做。

相关问题