2014-11-02 73 views
3

我有一些在最終類中有靜態方法的代碼。我試圖嘲笑這種方法。我曾嘗試做一些事情..如何在最終類中模擬靜態方法

public final Class Class1{ 

public static void doSomething(){ 
    } 
} 

我該如何模擬doSomething()?我曾嘗試..

Class1 c1=PowerMockito.mock(Class1.class) 
PowerMockito.mockSatic(Class1.class); 
Mockito.doNothing().when(c1).doSomething(); 

這給了我一個錯誤:

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here: 
-> at com.cerner.devcenter.wag.textHandler.AssessmentFactory_Test.testGetGradeReport_HTMLAssessment(AssessmentFactory_Test.java:63) 

E.g. thenReturn() may be missing. 
Examples of correct stubbing: 
    when(mock.isOk()).thenReturn(true); 
    when(mock.isOk()).thenThrow(exception); 
    doThrow(exception).when(mock).someVoidMethod(); 
Hints: 
1. missing thenReturn() 
2. you are trying to stub a final method, you naughty developer! 

    at org.powermock.api.mockito.internal.invocation.MockitoMethodInvocationControl.performIntercept(MockitoMethodInvocationControl.java:260) 

回答

0

最常用的測試框架是JUnit 4中所以,如果你使用它,你需要註釋測試類:

@RunWith(PowerMockRunner.class) 
@PrepareForTest(Class1.class) 

PowerMockito.mockSatic(Class1.class); 
Mockito.doNothing().when(c1).doSomething(); 

Mockito.when(Class1.doSomething()).thenReturn(fakedValue); 

// call of static method is required to mock it 
PowerMockito.doNothing().when(Class1.class); 
Class1.doSomething(); 
+0

我試過這樣做,但沒有成功。 在我的情況下,我正在編寫'Class2'的測試用例,它有一些使用'Class1'的方法。 Class1是最終的。我想在'Class1'裏面模擬的方法是靜態的。 – 2017-07-12 07:08:13

0

我用PowerMock。讓你做Mockito不能做的事情吧。 https://github.com/powermock/powermock/wiki

@RunWith(PowerMockRunner.class) 
@PrepareForTest(StaticClass.class) 
public class StaticTest { 

@Before 
public void setUp() { 
    PowerMockito.mockStatic(Bukkit.class); 

    //When a static method with no arguments is called. 
    when(StaticClass.callMethod1()).thenReturn(value); 

    //When a static method with an argument is called. 
    when(StaticClass.callMethod2(argument)).thenReturn(value2); 

    //Use when you don't care what the argument is.. 
    //use Mockito.anyInt(), Mockito.anyDouble(), etc. 

    when(StaticClass.callMethod3(Mockito.anyString())).thenReturn(value3); 
    } 

@Test 
public void VerifyStaticMethodsWork() { 
    assertEquals(value, StaticClass.callMethod1()); 
    assertEquals(value2, StaticClass.callMethod2(argument)); 
    assertEquals(value3, StaticClass.callMethod3("Hello")); 
} 

} 
相關問題