How do I setup a DataSource in Embedded GlassFish when using Arquillian?

Glassfish embedded/full will refer to a domain.xml file where can specify datasources, connection pools etc. that you can use for your tests.

 

1) Configure the test container by placing arquillian.xml in the root classpath (of your tests). Arquillian will build the configuration from this file instead of using the defaults. (as of Arquillian 1.0.0.Alpha2)

 

Sample arquillian.xml

 

<?xml version="1.0"?>
<arquillian xmlns="http://jboss.com/arquillian"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:glassfish="urn:arq:org.jboss.arquillian.container.glassfish.embedded_3">
   <glassfish:container>
      <glassfish:bindPort>9090</glassfish:bindPort>
      <glassfish:instanceRoot>src/test/glassfish</glassfish:instanceRoot>
      <glassfish:autoDelete>false</glassfish:autoDelete>
   </glassfish:container>
</arquillian>

 

2) You will want the embedded GlassFish container instance root to be at a fixed location so that you can setup your connection pools, jndi resources and other stuff in the domain.xml file e.g. src/test/glassfish/config/domain.xml (create folder manually if you have to) You can copy from your GlassFish installation e.g. ${glassfish}/glassfish/domains/domain1/config/domain.xml and edit where necessary.

 

Example section with the jndi datasource setup for a test database

 

<domain>
   <applications />
   <resources>
      <jdbc-resource jndi-name="jdbc/helpdesk" pool-name="HelpdeskPool"
         object-type="user" enabled="true"/>
      <jdbc-connection-pool datasource-classname="org.h2.jdbcx.JdbcDataSource"
         name="HelpdeskPool" res-type="javax.sql.DataSource">
         <property name="Password" value="helpdesk"/>
         <property name="User" value="helpdesk"/>
         <property name="serverName" value="localhost"/>
         <property name="DatabaseName" value="helpdesk"/>
         <property name="url" value="jdbc:h2:tcp://localhost/~/helpdesk"/>
      </jdbc-connection-pool>
   </resources>
</domain>

 

Now, for example, you can refer to the test datasource e.g. jdbc/helpdesk from your persistence.xml

 

It seems it's not possible for Glassfish to automatically configure resources from sun-resources.xml bundled in archive together with an app. Some reasons for keeping that file in a project are:

  • facilitating resource creation using CLI ('asadmin create-resources' command)
  • allowing the IDE <-> AppServer integration plugin to create resources before deploying the app (as it is done e.g. in NetBeans)