如何在RCP应用程序中使用Mockito测试异常?

时间:2018-07-23 04:50:29

标签: junit mockito swt rcp

我的向导类的performFinish()方法中有以下代码:

public boolean performFinish() {

    try {
      getContainer().run(true, false, changeArtifactRunnable());
    }
    catch (InvocationTargetException | InterruptedException e) {
      LoggerClass.logException(e);
    }

我想使用Mockito测试InvocationTargetExceptionInterruptedException的异常。 在上面的代码中,getContainer()方法来自org.eclipse.jface.wizard.Wizard类和

public void run(boolean fork, boolean cancelable,
            IRunnableWithProgress runnable) throws InvocationTargetException,
            InterruptedException;

该方法来自org.eclipse.jface.operation.IRunnableContext类。

如何在performFinish()方法中测试两个异常?

1 个答案:

答案 0 :(得分:0)

您可以使用 expected 关键字。例如:

@Test(expected = InvocationTargetException.class)
public void testInvocationTargetException()    {
    \\Invoke the method to be tested under the conditions, such that InvocationTargetException is thrown by it. No need of any assert statements
}

================================================ =========================== 编辑:

    @RunWith(MockitoJUnitRunner.class)
    public class EditArtifactWizardTest    {
        @Spy 
        //use correct constructor of EditArtifactWizard 
        private EditArtifactWizard editArtifactWizardSpy=Mockito.spy(new EditArtifactWizard ());
           @Test(expected = InvocationTargetException.class)
        public void testInvocationTargetException()    {
            \\Invoke the method to be tested under the conditions, such that InvocationTargetException is thrown by it. No need of any assert statements
            Mockito.when(editArtifactWizardSpy.getContainer()).thenThrow(InvocationTargetException.class);
            editArtifactWizardSpy.performFinish();
        }
    }

您可以创建EditArtifactWizard类的间谍并模拟getContainerMethod的行为。

P.S:由于我没有使用任何编辑器,请原谅输入错误或编译错误。