I have a small command line utility project that I'm using Maven to manage. The utility is a very simple app to populate a Velocity template and dump the results to a new file. My problem is where to put my Velocity templates. When I put them in src/test/resources/foo/bar/baz
, mvn test
fails because it can't find the referenced template, even though it is clearly there in target/classes/foo/bar/baz
, which is where the .class
file for the test and the class under test are located. If I put the template in the top-level directory of the project, the test passes, but then I'm not following the Maven project structure, and I suspect that the actual packaged .jar file wouldn't function. What am I missing?
UPDATE:
Method under test:
public final void mergeTemplate(final String templateFileName, final Writer writer) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException, Exception {
Velocity.init();
Velocity.mergeTemplate(templateFileName, Charset.defaultCharset().name(), context(), writer);
}
Test method:
@Test
public void testMergeTemplate() throws Exception {
final FooGenerator generator = new FooGenerator();
final StringWriter writer = new StringWriter();
generator.mergeTemplate("foo.yaml", writer);
Assert.assertEquals("Something went horribly, horribly wrong.", EXPECTED_RESULT, writer.toString().trim());
}
The only place I can place foo.yaml
and have the tests pass is in the root directory of the project, i.e., as a peer of src
and target
.
I have tried Velocity.setProperty() to set the properties similar to what was said above by @Jin Kim and was able to run it.
You could just configure Velocity to use the ClasspathResourceLoader, instead of the default FileResourceLoader.
You should put them in src/main/resources/foo/bar/baz because they need to be included in the main jar file.
So it turns out that instead of using something like
I should use something like
You can programmatically configure TEMPLATE_ROOT as follows: