Reputation: 1930
I have a function which I would like to test if it throws an exception as so :
@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;
}
The test I wrote was this :
@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);
}
Now when I run the test I get > AssertionError: excepted exception :workflowException, even though I can see(debug) that the workflowException was thrown .
I did read this question which was kind of similar : Testing for Exceptions using JUnit. Test fails even if the Exception is caught
But the answer says that I have to skip the try catch block ,which is something I don't want to do.
Also, the whole point of the test is to be sure the exception is caught , I know this seems like I testing for the implementation rather then the API but I don't want to trigger the actual exception as that would warrant for calling the actual service
Upvotes: 2
Views: 1043
Reputation: 131346
You want to ensure that your code catches WorkflowException
?
But you have already this here :
doThrow(new WorkflowException("test workflow exception"))
.when(workflowTaskService).completeTask(any(), any(), any());
If the test execution doesn't raise an exception, it means that the risen exception in this mocking operation was caught.
So @Test(expected=WorkflowException.class)
should not be specified.
If you want to be sure that the mocking method was performed, you can still verify that workflowTaskService.completeTask()
was invoked. And if it was invoked, it means the exception was thrown.
Upvotes: 2