【问题标题】:How do I mock a static method in final class如何在最终类中模拟静态方法
【发布时间】:2014-12-29 07:39:54
【问题描述】:

我有一些代码在 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)

【问题讨论】:

    标签: unit-testing mockito static-methods final


    【解决方案1】:

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

    【讨论】:

    • 我试过这样做,但没有成功。就我而言,我正在为Class2 编写测试用例,它有一些使用Class1 的方法。 Class1 是最终的。我想在Class1 中模拟的方法是静态最终的。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      相关资源
      最近更新 更多