【问题标题】:PowerMockito fails intermittently to mock final void method for an abstract classPowerMockito 间歇性地无法模拟抽象类的最终 void 方法
【发布时间】:2014-05-13 07:22:04
【问题描述】:

我正在使用 TestNG 6.8.8、Mockito 1.9.5 和 PowerMock 1.5.4。当我模拟最终的 void 方法时,测试有时会通过,有时会失败并出现错误 UnfinishedStubbingException。

这是一个 PowerMock 错误吗?

public abstract class Parent implements Serializable {
  protected abstract void validate();

  public final void validateSomething() {
    // some code here
  }
}

@PrepareForTest({ Parent.class })
public class ParentTest {
  @Test
  public final void testSomeMethod() {
    Parent parentObj = PowerMockito.mock(Parent.class);
    doNothing().when(parentObj).validateSomething();

    TestCodeThatResultsInCallToParentObj.validateSomething();
  }
}

错误信息:

org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)
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 mocking testng mockito powermock


    【解决方案1】:

    您可以使用委托并将该类的执行包装在您的类中。

    class ParentWrapper {
        private final Parent delegate;
    
        ParentWrapper(Parent delegate) { 
            this.delegate = delegate; 
        }
    
        void validateSth() {
            delegate.validateSth();
        }
    
    }
    

    现在您可以在没有任何 Powermock 的情况下模拟 ParentWrapper。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-21
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多