Laurens
Laurens

Reputation: 2088

Using a different persistence unit for testing

I have several stateless session beans I have created unit tests for. When I run these tests in the embedded GlassFish container, the default persistence unit for my project is used, which is a local MySQL database for development purposes. When running the unit tests however, I wish to use the embedded Derby database so that any unit testing does not clutter the database with mock data.

In OpenEJB, it is possible to override persistence.xml by creating a hash map and putting some properties, like so:

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);

Is the same or something similar possible with Sun's implementation to run unit tests on a different database?

Edit: I am using Ant to build the project. I guess it would be possible to copy the testing persistence.xml when running a test, and copy the regular persistence.xml for deployments but this seems clunky. Would switching to Maven be advisable?

Upvotes: 2

Views: 1774

Answers (1)

carlspring
carlspring

Reputation: 32597

I don't know what sort of build tool you're using.

In Maven you have a separation between runtime and test resources:

project 
 |- src/main/resources
 |- src/test/resources

The ones in src/test/resources aren't included in your final artifact and are only used by the unit testing plugin (Surefire) during the testing phase of the build.

Whatever the tool, I suggest you have this sort of separation between the resources in order to be able to achieve the result you're looking for.

Upvotes: 3

Related Questions