Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure embedded OpenEJB container for tests properly?

This is my SLSB:

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

This is my persistence.xml (I'm using Glassfish v3):

<persistence>
  <persistence-unit name="abc">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>java:/MyDS</jta-data-source>
    <properties>
        <property name="hibernate.archive.autodetection" value="class" />
        <property name="hibernate.dialect"
          value="org.hibernate.dialect.MySQLInnoDBDialect" />
    </properties>
  </persistence-unit>
</persistence>

Now I'm trying to create a test, using OpenEJB embedded container. This is my test class:

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
  }
}

I would like to use HSQL for testing. How can I instruct OpenEJB that my persistence unit "abc" has to point to HSQL during testing? Shall I create a new version of persistence.xml? Shall I use openejb.xml? I'm lost in their examples and documentation.. :(

It's a Maven-3 project.

like image 415
yegor256 Avatar asked Oct 28 '10 11:10

yegor256


1 Answers

I would suggest placing a file named jndi.properties in src/test/resources for your OpenEJB configuration. This will then be available in the test classpath, you can then use the no-argument contructor of InitialContext to lookup datasources and ejbs. An example configuration looks like this, I'm using mysql for my datasource:

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 should then automatically replace the reference in persistence.xml with this datasource, if this is the only datasource then this should work even if the names are different.

Edit: Persistence unit settings

According to the documentation you referenced it should also be possible to configure persistence unit properties through jndi.properties:

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

I haven't tested this myself since I'm using mysql for both tests and normal executions, only with different database names. Please let me know if this works, I've been thinking about replacing mysql in my testcases too.

like image 181
Jörn Horstmann Avatar answered Oct 31 '22 14:10

Jörn Horstmann