package example; import freemarker.template.Template; import freemarker.template.TemplateException; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class FreemarkerTest { public static final String TEMPLATE_NAME = "HELLO_WORLD"; public Optional hello(String name) { if (name == null) { return Optional.empty(); } String templateStr = "Hello, ${name}"; Reader reader = new StringReader(templateStr); StringWriter writer = new StringWriter(); Template template; try { template = new Template(TEMPLATE_NAME, reader); } catch (IOException e) { return Optional.empty(); } Map model = new HashMap<>(); model.put("name", name); try { template.process(model, writer); } catch (TemplateException e) { System.err.println(e.getMessage()); return Optional.empty(); } catch (IOException e) { System.err.println(e.getMessage()); return Optional.empty(); } return Optional.ofNullable(writer.toString()); } @Test void processTemplateTest() { assertTrue(hello(null).isEmpty()); assertTrue(hello("Fabian").isPresent()); assertEquals("Hello, World", hello("World").get()); } }