如何使用PowerMockito模拟私有静态方法?
我正在尝试模拟私有静态方法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
我想我嘲笑的东西我做错了。 任何想法我该如何解决?
为此,您可以使用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"); } }
希望它能帮到你。
如果anotherMethod()将任何参数作为anotherMethod(参数),则方法的正确调用将是:
PowerMockito.doReturn("abc").when(Util.class, "anotherMethod", parameter);
我不确定您使用的是哪个版本的PowerMock,但是对于更高版本,您应该使用@RunWith(PowerMockRunner.class) @PrepareForTest(Util.class)
说到这一点,我发现使用PowerMock确实存在问题,这是设计糟糕的可靠迹象。 如果你有时间/机会改变设计,我会先尝试做。