maven 多module时测试springmvc+freemarker的问题总结

相关问题:

http://www.iteye.com/problems/95405

http://www.iteye.com/problems/74168 (该问题给出的方案是使用classpath)

原因分析:

比如你的maven工程是如下所示,包含很多子module:

test

  test-core

  test-web

如果在test-web中测试springmvc的项目时,会发现当前工作目录仍然是test 而不是test-web;所以问题就是出在这。

接下来提供几个方案:

1、绝对路径方式:

@WebAppConfiguration(value = "file:E:\\test\\test-web\\src\\main\\webapp")

FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();

configurer.setTemplateLoaderPath("file:E:\\lion\\lion-web\\src\\main\\webapp")

缺点很明显,如果需要在win/linux上切换 很痛苦

2、类路径方式:

@WebAppConfiguration(value = "classpath:template")

FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();

configurer.setTemplateLoaderPath("classpath:template");

缺点也是比较明显,需要复制两份模板。

3、通过获取webapp目录路径的方式:

FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();

String path = FreeMarkerConfig.class.getClassLoader().getResource(".").toString().substring(6);

String webappPath = path.replace("/target/test-classes/", "");

webappPath = webappPath.replace(wac.getServletContext().getRealPath(""), "");

webappPath = webappPath + "/src/main/webapp";

configurer.setTemplateLoaderPath("file:" + webappPath);

思路就是:先获取当前的测试类编译到的路径,然后往上获取到根,再拼上src/main/webapp即可拿到目录。

所以3更通用些。

如果你只需要使用maven test 运行:更好的方案是:

1、在test-web的pom.xml中添加

                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <configuration>
                            <systemProperties combine.children="append">
                                <property>
                                    <name>modulePath</name>
                                    <value>${project.basedir}</value>
                                </property>
                            </systemProperties>
                        </configuration>
                    </plugin>

project.basedir就是当前模块的目录。 

然后在测试类中通过:System.getProperty("modulePath"); 即可拿到该路径,但是如果在如idea集成环境中不好用。

还一种方案是如在idea中使用(具体没有测试):

Run->Edit configuration->Defaults->JUnit->Working directory set the value$MODULE_DIR$ and Intellij will set the relative path in all junits just like Maven.

http://stackoverflow.com/questions/5637765/how-to-deal-with-relative-path-in-junits-between-maven-and-intellij

从如上方案中可以看出,【3】是最通用的方案。

猜你喜欢

转载自jinnianshilongnian.iteye.com/blog/1878877