問題描述
我正在設置模擬類的靜態方法.我必須在 @Before
注釋的 JUnit 設置方法中執行此操作.
I'm setting up mocking a class' static methods. I have to do this in a @Before
-annotated JUnit setup method.
我的目標是設置類來調用真正的方法,除了那些我明確模擬的方法.
My goal is to setup the class to call real methods, except for those methods I explicitly mock.
基本上:
@Before
public void setupStaticUtil() {
PowerMockito.mockStatic(StaticUtilClass.class);
// mock out certain methods...
when(StaticUtilClass.someStaticMethod(anyString())).thenReturn(5);
// Now have all OTHER methods call the real implementation??? How do I do this?
}
我遇到的問題是在 StaticUtilClass
方法 public static int someStaticMethod(String s)
不幸地拋出了一個 RuntimeException
如果提供 null
值.
The problem I'm running into is that within StaticUtilClass
the method public static int someStaticMethod(String s)
unfortunately throws a RuntimeException
if supplied with a null
value.
所以我不能簡單地將調用真實方法作為默認答案的明顯路線如下:
So I can't simply go the obvious route of calling real methods as the default answer as below:
@Before
public void setupStaticUtil() {
PowerMockito.mockStatic(StaticUtilClass.class, CALLS_REAL_METHODS); // Default to calling real static methods
// The below call to someStaticMethod() will throw a RuntimeException, as the arg is null!
// Even though I don't actually want to call the method, I just want to setup a mock result
when(StaticUtilClass.someStaticMethod(antString())).thenReturn(5);
}
我需要設置默認答案以在所有其他靜態方法上調用真實方法之后我模擬了我感興趣的方法的結果.
I need to set the default Answer to call real methods on all other static methods after I mock the results from the method I'm interested in mocking.
這可能嗎?
推薦答案
你在找什么叫做partial mocking.
在 PowerMock 中你可以使用 mockStaticPartial 方法.
In PowerMock you can use mockStaticPartial method.
在 PowerMockito 中,您可以使用存根,它只會存根定義的方法,而其他保持不變:
In PowerMockito you can use stubbing, which will stub only the method defined and leave other unchanged:
PowerMockito.stub(PowerMockito.method(StaticUtilClass.class, "someStaticMethod")).toReturn(5);
也別忘了
@PrepareForTest(StaticUtilClass.class)
這篇關于PowerMock,模擬一個靜態方法,然后在所有其他靜態上調用真實方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!