As in many Java apps, we're using Freemarker in our app to render emails. We've found that some of our templates weren't rendering exactly as we thought they would, and so we realized that we ought to write some unit tests for our template rendering. Well I set up the tests, and immediately received a FileNotFoundException: Template "my/template.ftl" not found.
I figured that this must be both a solved problem with an easy solution. That was many work hours ago, and I realized that I was wrong; from what I can tell, this is neither solved nor easy!
Our app's setup is, I think, pretty standard. We have a Maven project, and store our Freemarker templates in src/main/webapp/WEB-INF/freemarker. Although most of our app's functionality is initiated by Quartz jobs, we deploy it as a webapp. Therefore the following configuration in our spring XML file is all that we need:
<bean id="freemarkerConfiguration"
class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
<property name="templateLoaderPath" value="/WEB-INF/freemarker/" />
</bean>
Then in our code, we Autowire the bean in like so:
@Autowired
protected Configuration freemarkerConfiguration;
and use it like so:
Template template = freemarkerConfiguration.getTemplate("mail/job/detail.ftl");
That works great in the context of our deployed app, executing within a Quartz job. But we always get the template not found when running from within unit tests.
I tried many different approaches, none of which worked. The last involved creating my own Freemarker TemplateLoader implementation, and trying to get it to load the Freemarker template files form the classpath. The problems with that approach are that a) the same classloading code that I successfully use elsewhere in tests would not find the template, b) I'm not sure all that is involved with correctly implementing a TemplateLoader, and c) this all just seems overly-complicated in general.
I may continue this route, but first... am I missing something obvious? One of Freemarker's benefits is that it doesn't require an HTTP context, so why would it be so difficult to use Freemarker outside of a web app context?