FreemarkerUtil { public static <T> T getAsObject(TemplateModel model, Class<T> type, T defaultValue) { try { T retValue = defaultValue; if (model != null) { @SuppressWarnings("unchecked") T value = (T) DeepUnwrap.unwrap(model); if (value != null) { retValue = value; } } return retValue; } catch (TemplateModelException e) { throw new FreemarkerAutotagException("Cannot unwrap a model", e); } } private  FreemarkerUtil(); static T getAsObject(TemplateModel model, Class<T> type, T defaultValue);  }
@Test(expected = FreemarkerAutotagException.class) public void testGetAsObjectException() throws TemplateModelException { TemplateNumberModel model = createMock(TemplateNumberModel.class); Template template = createMock(Template.class); TemplateHashModel rootDataModel = createMock(TemplateHashModel.class); Writer out = createMock(Writer.class); expect(model.getAsNumber()).andThrow(new TemplateModelException()); expect(template.getMacros()).andReturn(new HashMap<String, Macro>()); replay(template, rootDataModel, out); new Environment(template, rootDataModel, out); replay(model); try { assertEquals(new Integer(42), FreemarkerUtil.getAsObject(model, Integer.class, new Integer(1))); } finally { verify(template, rootDataModel, out, model); } }
@Test public void testGetAsObject() throws TemplateModelException { TemplateNumberModel model = createMock(TemplateNumberModel.class); Template template = createMock(Template.class); TemplateHashModel rootDataModel = createMock(TemplateHashModel.class); Writer out = createMock(Writer.class); expect(model.getAsNumber()).andReturn(new Integer(42)); expect(template.getMacros()).andReturn(new HashMap<String, Macro>()); replay(template, rootDataModel, out); new Environment(template, rootDataModel, out); replay(model); assertEquals(new Integer(42), FreemarkerUtil.getAsObject(model, Integer.class, new Integer(1))); verify(template, rootDataModel, out, model); }
@Test public void testGetAsObjectDefault() throws TemplateModelException { Template template = createMock(Template.class); TemplateHashModel rootDataModel = createMock(TemplateHashModel.class); Writer out = createMock(Writer.class); expect(template.getMacros()).andReturn(new HashMap<String, Macro>()); replay(template, rootDataModel, out); new Environment(template, rootDataModel, out); assertEquals(new Integer(1), FreemarkerUtil.getAsObject(null, Integer.class, new Integer(1))); verify(template, rootDataModel, out); }