TemplateHelper { public String replace(String text, String values) { if (params == null) { return text; } JsonObject obj = parseValues(values); for (TemplateParam p : params) { String value = "-missing value-"; if (obj != null && obj.has(p.getKey())) { value = obj.get(p.getKey()).getAsString(); if ("file".equalsIgnoreCase(p.getType())) { value = "/s/api/fileservice/files/" + value + "/content"; } } else if ("file".equalsIgnoreCase(p.getType())) { value = "/ui/img/image_preview.png"; } text = StringUtils.replace(text, "{{" + p.getKey() + "}}", value); } return text; } TemplateHelper(String params); String replace(String text, String values); boolean containsFile(File file, String values);  }
@Test public void testSimpleReplace() throws Exception { assertEquals("<div>value2</div>value3", helper.replace("<div>{{key2}}</div>{{key3}}", values)); }
@Test public void testMultiReplace() throws Exception { assertEquals("<div>value2</div>value2value3", helper.replace("<div>{{key2}}</div>{{key2}}{{key3}}", values)); }
@Test public void testImage() throws Exception { String testValues = "{key1:42, key2:\"value2\", key3:\"value3\"}"; assertEquals("<div>/s/api/fileservice/files/42/content</div>value3", helper.replace("<div>{{key1}}</div>{{key3}}", testValues)); }
@Test public void testImagePlaceholder() throws Exception { assertEquals("<div>/ui/img/image_preview.png</div>value3", helper.replace("<div>{{key1}}</div>{{key3}}", values)); }
@Test public void testMissingParameters() throws Exception { helper = new TemplateHelper(null); assertEquals("<div>{{key2}}</div>{{key3}}", helper.replace("<div>{{key2}}</div>{{key3}}", values)); helper = new TemplateHelper(""); assertEquals("<div>{{key2}}</div>{{key3}}", helper.replace("<div>{{key2}}</div>{{key3}}", values)); }
@Test public void testMissingValues() throws Exception { assertEquals("<div>-missing value-</div>-missing value-", helper.replace("<div>{{key2}}</div>{{key3}}", null)); assertEquals("<div>-missing value-</div>-missing value-", helper.replace("<div>{{key2}}</div>{{key3}}", "")); assertEquals("<div>/ui/img/image_preview.png</div>-missing value-", helper.replace("<div>{{key1}}</div>{{key3}}", null)); }
@Test public void testMissingText() throws Exception { assertEquals(null, helper.replace(null, values)); assertEquals("", helper.replace("", values)); }
@Test(expected = IllegalStateException.class) public void testCrappyValues() throws Exception { String testValues = "crappy_values"; assertEquals("<div>value2</div>value3", helper.replace("<div>{{key2}}</div>{{key3}}", testValues)); }