我有一个函数,我想测试它是否会抛出异常:
@Override
public WorkOrderTask updateWorkOrderTaskWithOutcome(String taskId, String outcome, WorkOrderTask workOrderTask) {
Map<String, Object> variables = new HashMap<>();
if (!outcome.equals(TaskOutcomes.CANCEL.getValue())) {
WorkOrderType workOrder = workOrderTask.getWorkOrderPayload().getWorkOrder();
workOrder = workflowDataService.updateWorkOrder(workOrder);
workOrderTask.getWorkOrderPayload().setWorkOrder(workOrder);
variables = getProcessVariables(workOrder);
}
try {
workflowTaskService.completeTask(taskId, outcome, variables);
logger.debug("Updated Task ID: {} with outcome {}", taskId, outcome);
} catch (WorkflowException e) {
logger.error("Updating Work Order Task ID: {} with outcome {} FAILED", taskId, outcome, e);
}
return workOrderTask;
}
我写的测试是这样的:
@Test(expected=WorkflowException.class)
public void testUpdateWorkOrderTaskForWorkflowException() throws Exception {
WorkOrderTask workOrderTask = GrcWorkflowTestUtil.generateWorkOrderTask();
WorkOrderType workOrder = workOrderTask.getWorkOrderPayload().getWorkOrder();
doReturn(workOrder).when(workflowDataService).updateWorkOrder(workOrder);//some mock stubs to avoid calling actual service
doThrow(new WorkflowException("test workflow exception")).when(workflowTaskService).completeTask(any(), any(), any());//forcing the exception to be thrown
WorkOrderTask workOrderTaskRet = workOrderService.updateWorkOrderTaskWithOutcome(TestEnvironmentUtil.TASK_ID,
TaskOutcomes.SUBMIT.getValue(), workOrderTask);
}
现在,当我运行测试时,我得到&gt; AssertionError:例外异常:workflowException,即使我可以看到(调试)抛出了workflowException。
我确实读过这个类似的问题: Testing for Exceptions using JUnit. Test fails even if the Exception is caught
但答案是说我必须跳过try catch块,这是我不想做的事情。
此外,测试的全部要点是确保异常被捕获,我知道这似乎是我测试实现而不是API,但我不想触发实际异常,因为那样调用实际服务的保证
答案 0 :(得分:2)
您想确保代码捕获WorkflowException
吗?
但你已经在这里了:
doThrow(new WorkflowException("test workflow exception"))
.when(workflowTaskService).completeTask(any(), any(), any());
如果测试执行没有引发异常,则意味着捕获了此模拟操作中的上升异常
因此,不应指定@Test(expected=WorkflowException.class)
。
如果您想确保执行了模拟方法,您仍然可以验证是否已调用workflowTaskService.completeTask()
。如果它被调用,则意味着抛出了异常。