title: Freemarker and Spring in JUnit tests
body: <p>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: <em>Template "my/template.ftl" not found.</em></p>
  
  <p>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!</p>
  
  <p>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:</p>
  
  <pre><code>&lt;bean id="freemarkerConfiguration"
      class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean"&gt;
      &lt;property name="templateLoaderPath" value="/WEB-INF/freemarker/" /&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>Then in our code, we Autowire the bean in like so:</p>
  
  <pre><code>@Autowired
  protected Configuration freemarkerConfiguration;
  </code></pre>
  
  <p>and use it like so:</p>
  
  <pre><code>Template template = freemarkerConfiguration.getTemplate("mail/job/detail.ftl");
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>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?</p>