簡體   English   中英

如何在最終類中模擬靜態方法

[英]How do I mock a static method in final class

我有一些代碼在final類中有一個靜態方法。 我試圖嘲笑那種方法。 我嘗試過做一些事情..

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)

最常用的測試框架是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();

我使用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"));
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM