如何指示Maven忽略我的main / resources / persistence.xml以支持test / …?

为了测试,我有两个persistence.xml文件:

  • src/main/resources/META-INF/persistence.xml
  • src/test/resources/META-INF/persistence.xml

如何指示Maven在测试期间忽略第一个文件? 现在它不会被忽视,因为OpenEJB说:

 ERROR - FAIL ... Finder: @PersistenceContext unitName has multiple matches: unitName "abc" has 2 possible matches. 

查看针对您尝试执行的操作的备用描述符function。

试试这个设置:

  • src/main/resources/META-INF/persistence.xml
  • src/main/resources/META-INF/test.persistence.xml

然后,您可以通过设置openejb.altdd.prefix系统或InitialContext属性来构建OpenEJB以test.persistence.xml选择test.persistence.xml文件

另一种可能的解决方案是覆盖测试中的持久性单元属性 。 使用这种方法,您可以避免使用第二个persistence.xml ,这可能很好,因为维护两个可能很痛苦。

您可以使用Maven方法,但请注意,根据规范,持久性提供程序只会在找到persistence.xml的确切jar或目录中查找(也称扫描) @Entity bean。 所以要敏锐地意识到在Maven中有两个不同的位置:

  • target/classes
  • target/test-classes

编辑有关最重要function的更多详细信息

您可以通过系统属性或初始上下文属性(包括jndi.properties文件)覆盖测试设置中的任何属性。 格式为:

 .= 

例如,使用以下persistence.xml

   org.hibernate.ejb.HibernatePersistence movieDatabase movieDatabaseUnmanaged       

您可以在测试用例中覆盖添加持久性单元属性。 目前没有可以移除它们的设施(如果您有需要,请告诉我们 – 到目前为止还没有真正实现)。

 Properties p = new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory"); p.put("movie-unit.hibernate.hbm2ddl.auto", "update"); p.put("movie-unit.hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); context = new InitialContext(p); 

或者通过jndi.properties文件

 java.naming.factory.initial=org.apache.openejb.client.LocalInitialContextFactory movie-unit.hibernate.hbm2ddl.auto = update movie-unit.hibernate.dialect = org.hibernate.dialect.HSQLDialect 

我想你可以在你的pom.xml中创建两个配置文件:

  dev    prod  test    

之后,在您的src文件夹中,创建两个名为dev / resoruces和test / resources的文件夹,并在那里复制您的不同资源。 之后,添加如下内容:

   ${basedir}/src/main/resources false   ${basedir}/src/main/${environment}/resources true   

$ {basedir}取决于命令行参数,它可以是test或dev。 你可以像这样运行maven命令: mvn clean package -P test

我一直在测试这些和其他类似的解决方案而不涉及pom.xml …在我看来,解决这个问题的最好方法是有两个application-context.xml(一个只用于测试类)和在测试的application-context.xml中添加自定义持久性单元管理器bean。 像这个例子:

   classpath*:META-INF/test.persistence.xml    

此解决方案运行。 🙂

更好地添加两个文件 – 通常,在构建中进行测试/生产或调试/配置文件/生产区分只会带来麻烦。 最好尝试使用不同的perasistence单位名称进行生产(比如abc-production)和测试(abc-tests)。