如何正确配置嵌入式OpenEJB容器以进行测试?

这是我的SLSB:

@Stateless public class MyService { PersistenceContext(unitName = "abc") EntityManager em; public boolean exists(int id) { return this.em.find(Employee.class, id) != null; } } 

这是我的persistence.xml (我正在使用Glassfish v3):

   org.hibernate.ejb.HibernatePersistence java:/MyDS       

现在我正在尝试使用OpenEJB嵌入式容器创建测试。 这是我的测试类:

 class MyServiceText { @Test public void testChecksExistence() throws Exception { Properties properties = new Properties(); properties.setProperty( javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory" ); InitialContext ic = new InitialContext(properties); // actual testing skipped } } 

我想用HSQL进行测试。 如何指示OpenEJB我的持久性单元"abc"在测试期间必须指向HSQL? 我要创建一个新版本的persistence.xml吗? 我要用openejb.xml吗? 我在他们的例子和文档中迷失了.. 🙁

这是一个Maven-3项目。

我建议在src/test/resources为您的OpenEJB配置放置一个名为jndi.properties的文件。 然后,这将在测试类路径中可用,然后您可以使用InitialContext的无参数构造函数来查找数据源和ejbs。 示例配置如下所示,我正在使用mysql作为我的数据源:

 java.naming.factory.initial=org.apache.openejb.client.LocalInitialContextFactory myDS=new://Resource?type=DataSource myDS.JdbcDriver=com.mysql.jdbc.Driver myDS.JdbcUrl=jdbc:mysql://127.0.0.1:3306/test myDS.JtaManaged=true myDS.DefaultAutoCommit=false myDS.UserName=root myDS.Password=root 

然后,OpenEJB应该自动将persistence.xml中的引用替换为此数据源,如果这是唯一的数据源,那么即使名称不同,这也应该有效。

编辑:持久性单位设置

根据您引用的文档 ,还应该可以通过jndi.properties配置持久性单元属性:

 abc.hibernate.hbm2ddl.auto=update abc.hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect 

我没有自己测试过,因为我使用mysql进行测试和正常执行,只有不同的数据库名称。 如果有效,请告诉我,我一直在考虑在我的测试用例中替换mysql。