PowerMockito:doThrow未完成的存根

时间:2014-11-03 19:17:25

标签: java unit-testing junit powermock

我试图通过抛出异常来模拟JUnit测试中的失败情况。但是,似乎我没有正确地存储某些方法。

我的代码如下:

private MyClass mockObject;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    mockObject = PowerMockito.mock(MyClass.class);
    whenNew(MyClass.class).withAnyArguments().thenReturn(mockObject);
}

@Test
public void testFailure() throws Exception {
    PowerMockito.doThrow(new Exception("This is a test exception.")).when(mockObject).register(anyString());
    ...
}

,其中register的返回类型为void

但是,当我执行此测试时,我会在doThrow调用中收到未完成的存根异常。

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!

任何人都可以帮助确定我在这里缺少的东西吗?

如果它有帮助,我的pom中的powermock-api-mockito和powermock-module-junit4的依赖版本为1.5.6。

1 个答案:

答案 0 :(得分:0)

问题结果是与此代码无关的静态模拟。我有mockStatic(AnotherClass.class); doNothing()时(AnotherClass.class)。在@BeforeClass方法中。删除doNothing()行后,测试工作正常。谢谢大家的帮助。