2009-01-12 45 views
1

我有一个使用Maven管理的小型命令行实用程序项目。该实用程序是一个非常简单的应用程序,用于填充Velocity模板并将结果转储到新文件。我的问题是在哪里放置我的Velocity模板。当我将它们放入src/test/resources/foo/bar/baz时,mvn test因为找不到引用的模板而失败,尽管它明显存在于target/classes/foo/bar/baz中,这是测试文件和测试类所在的位置。如果我将模板放在项目的顶层目录中,测试通过了,但是我没有遵循Maven项目结构,我怀疑实际打包的.jar文件不起作用。我错过了什么?我应该在哪里放置用Maven构建的命令行实用程序的Velocity模板文件?

UPDATE:

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 
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()); 
} 

我可以把foo.yaml,并有测试的唯一的地方通过在该项目的根目录,即作为src的同行target

回答

0

所以事实证明,而不是使用像

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

我应该使用类似

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

您应该将它们放在src/main/resources/foo/bar/baz中,因为它们需要包含在主jar文件中。

+0

不够公平。现在我把它们放在哪里来让我的单元测试通过? – 2009-01-12 14:16:35

0

你可以只配置速度使用ClasspathResourceLoader,而不是默认的FileResourceLoader。

2

您可以通过编程配置TEMPLATE_ROOT如下:

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

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

我已经试过Velocity.setProperty()来设置类似于上面通过@Jin金正日说的属性,并能运行它。

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

ve.init(); 
相关问题