本文介紹了如何使用 PowerMockito 模擬私有靜態方法?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試模擬私有靜態方法 anotherMethod()
.見下面的代碼
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.
}
}
這是我的測試代碼
@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?
推薦答案
為此,您可以使用 PowerMockito.spy(...)
和 PowerMockito.doReturn(...)
.
To to this, you can use PowerMockito.spy(...)
and PowerMockito.doReturn(...)
.
此外,您必須在測試類中指定 PowerMock 運行器,并準備測試類,如下所示:
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");
}
}
希望對你有幫助.
這篇關于如何使用 PowerMockito 模擬私有靜態方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!