ForEachHandler implements OutputOperationHandler<ForEach<I, O>, Iterable<? extends O>> { @Override public Iterable<? extends O> doOperation(final ForEach<I, O> forEach, final Context context, final Store store) throws OperationException { if (null == forEach.getOperation()) { throw new OperationException("Operation cannot be null"); } if (null == forEach.getInput()) { throw new OperationException("Inputs cannot be null"); } final List<O> results = new ArrayList<>(); for (final I input : forEach.getInput()) { final Operation clonedOperation = forEach.getOperation().shallowClone(); OperationHandlerUtil.updateOperationInput(clonedOperation, input); results.add(executeOperation(clonedOperation, context, store)); } return results; }  @Override Iterable<? extends O> doOperation(final ForEach<I, O> forEach, final Context context, final Store store);  }
@Test public void shouldThrowExceptionWithNullOperation() { final Store store = mock(Store.class); final Context context = new Context(new User()); final ForEach op = new ForEach.Builder<>() .operation(null) .input(Arrays.asList("1", "2")) .build(); final ForEachHandler handler = new ForEachHandler(); try { handler.doOperation(op, context, store); fail("Exception expected"); } catch (final OperationException e) { assertTrue(e.getMessage().contains("Operation cannot be null")); } }
@Test public void shouldThrowExceptionWithNullInput() { final Store store = mock(Store.class); final Context context = new Context(new User()); final ForEach op = new ForEach.Builder<>() .operation(new GetElements()) .build(); final ForEachHandler handler = new ForEachHandler(); try { handler.doOperation(op, context, store); fail("Exception expected"); } catch (final OperationException e) { assertTrue(e.getMessage().contains("Inputs cannot be null")); } }
@Test public void shouldExecuteAndReturnExpected() throws OperationException { final Store store = mock(Store.class); final Context context = new Context(new User()); final InputOutput op = mock(InputOutput.class); final InputOutput opClone = mock(InputOutput.class); given(op.shallowClone()).willReturn(opClone); final Object input = mock(Object.class); final Object output = mock(Object.class); final ForEach forEach = new ForEach.Builder<>() .input(input) .operation(op) .build(); final ForEachHandler handler = new ForEachHandler(); given(store.execute(opClone, context)).willReturn(output); final List<Object> result = (List<Object>) handler.doOperation(forEach, context, store); verify(opClone).setInput(input); assertEquals(1, result.size()); assertSame(output, result.get(0)); }