問題描述
我正在為類似于下面給出的示例的方法編寫 JUnit 測試用例:
I am writing JUnit test case for methods similar to sample given below:
Class SampleA{
public static void methodA(){
boolean isSuccessful = methodB();
if(isSuccessful){
SampleB.methodC();
}
}
public static boolean methodB(){
//some logic
return true;
}
}
Class SampleB{
public static void methodC(){
return;
}
}
我在我的測試類中編寫了以下測試用例:
I wrote the following test case in my test class:
@Test
public void testMethodA_1(){
PowerMockito.mockStatic(SampleA.class,SampleB.class);
PowerMockito.when(SampleA.methodB()).thenReturn(true);
PowerMockito.doNothing().when(SampleB.class,"methodC");
PowerMockito.doCallRealMethod().when(SampleA.class,"methodA");
SampleA.methodA();
}
現在我想驗證是否調用了 Sample B 類的靜態方法 C().如何使用 PowerMockito 1.6 實現?我已經嘗試了很多東西,但它似乎對我來說并不奏效.任何幫助表示贊賞.
Now I want to verify whether static methodC() of class Sample B is called or not. How can I achieve using PowerMockito 1.6? I have tried many things but it doesn't seems to be working out for me. Any help is appreciated.
推薦答案
就個人而言,我不得不說 PowerMock 等是解決問題的解決方案,如果你的代碼還不錯的話,你不應該有.在某些情況下,它是必需的,因為框架等使用靜態方法會導致代碼根本無法測試,但如果是關于您的代碼,您應該始終更喜歡重構而不是靜態模擬.
Personally, I have to say that PowerMock, etc. is the solution to a problem that you shouldn't have if your code wasn't bad. In some cases, it is required because frameworks, etc. use static methods that lead to code that simply cannot be tested otherwise, but if it's about YOUR code, you should always prefer refactoring instead of static mocking.
無論如何,在 PowerMockito 中進行驗證應該不會那么難......
Anyway, verifing that in PowerMockito shouldn't be that hard...
PowerMockito.verifyStatic( Mockito.times(1)); // Verify that the following mock method was called exactly 1 time
SampleB.methodC();
(當然,要使其工作,您必須將 SampleB 添加到 @PrepareForTest
注釋并為其調用 mockStatic
.)
(Of course, for this to work you must add SampleB to the @PrepareForTest
annotation and call mockStatic
for it.)
這篇關于使用 PowerMockito 1.6 驗證靜態方法調用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!