views:

546

answers:

3

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.

+1  A: 

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

krosenvold
Fair enough. Now where do I put them to make my unit tests pass?
Hank Gay
They should pass in src/main, but you're not describing the reason they're failing..? Is it a multi-module project ?
krosenvold
It's a very basic, single-module project. I'll update the question with sample code.
Hank Gay
A: 

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);
Hank Gay
A: 

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

Nathan Bubna