Question

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.

Was it helpful?

Solution 3

So it turns out that instead of using something like

generator.mergeTemplate("foo.yaml", writer);

I should use something like

InputStream fooStream = getClass().getResourceAsStream("foo.yaml");
generator.mergeTemplate(fooStream, writer);

OTHER TIPS

You can programmatically configure TEMPLATE_ROOT as follows:

Properties props = new Properties();        
props.put("file.resource.loader.path", templateRootDir);

VelocityEngine engine = new VelocityEngine();
engine.init(props);
engine.evaluate(...);

You should put them in src/main/resources/foo/bar/baz because they need to be included in the main jar file.

You could just configure Velocity to use the ClasspathResourceLoader, instead of the default FileResourceLoader.

I have tried Velocity.setProperty() to set the properties similar to what was said above by @Jin Kim and was able to run it.

VelocityEngine ve = new VelocityEngine();
ve.setProperty(RunTimeConstants.RESOURCE_LOADER,"file");
ve.setProperty("file.resource.loader.path",templaterootdir);

ve.init();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top