### Question:
VelocityRenderer { public String render(String code) throws IconException { String namespace = "IconVelocityRenderer_" + Thread.currentThread().getId(); StringWriter output = new StringWriter(); VelocityEngine engine = null; try { engine = velocityManager.getVelocityEngine(); engine.startedUsingMacroNamespace(namespace); VelocityContext context = new XWikiVelocityContext(velocityManager.getVelocityContext()); if (engine.evaluate(context, output, "DefaultIconRenderer", code)) { return output.toString(); } else { throw new IconException("Failed to render the icon. See the Velocity runtime log.", null); } } catch (XWikiVelocityException e) { throw new IconException("Failed to render the icon.", e); } finally { if (engine != null) { engine.stoppedUsingMacroNamespace(namespace); } } }  String render(String code);  }### Answer:
@Test public void renderTest() throws Exception { VelocityEngine engine = mock(VelocityEngine.class); when(velocityManager.getVelocityEngine()).thenReturn(engine); when(engine.evaluate(any(VelocityContext.class), any(Writer.class), any(), eq("myCode"))).thenAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Writer writer = (Writer) invocation.getArguments()[1]; writer.write("Rendered code"); return true; } }); assertEquals("Rendered code", mocker.getComponentUnderTest().render("myCode")); verify(engine).startedUsingMacroNamespace("IconVelocityRenderer_" + Thread.currentThread().getId()); verify(engine).stoppedUsingMacroNamespace("IconVelocityRenderer_" + Thread.currentThread().getId()); }
@Test public void renderWithException() throws Exception { Exception exception = new XWikiVelocityException("exception"); when(velocityManager.getVelocityEngine()).thenThrow(exception); IconException caughtException = null; try { mocker.getComponentUnderTest().render("myCode"); } catch(IconException e) { caughtException = e; } assertNotNull(caughtException); assertEquals("Failed to render the icon.", caughtException.getMessage()); assertEquals(exception, caughtException.getCause()); }
@Test public void renderWhenEvaluateReturnsFalse() throws Exception { VelocityEngine engine = mock(VelocityEngine.class); when(velocityManager.getVelocityEngine()).thenReturn(engine); when(engine.evaluate(any(VelocityContext.class), any(Writer.class), any(), eq("myCode"))).thenReturn(false); IconException caughtException = null; try { mocker.getComponentUnderTest().render("myCode"); } catch(IconException e) { caughtException = e; } assertNotNull(caughtException); assertEquals("Failed to render the icon. See the Velocity runtime log.", caughtException.getMessage()); verify(engine).startedUsingMacroNamespace("IconVelocityRenderer_" + Thread.currentThread().getId()); verify(engine).stoppedUsingMacroNamespace("IconVelocityRenderer_" + Thread.currentThread().getId()); }