After reading more OpenEJB examples, I decided to set my test up as a
LocalClient, which gave me easy access to the entity manager and queries.
Here's a simplified prototype:
package com.mycompany.beans;
import java.util.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import junit.framework.TestCase;
// for injection
import org.apache.openejb.api.LocalClient;
import javax.ejb.EJB;
import javax.transaction.UserTransaction;
import javax.annotation.Resource;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.persistence.Query;
// My Session Beans
import com.mycompany.service.MyService;
import com.mycompany.beans.MyServiceBean;
// My Persistent Entities
import com.mycompany.domain.MyEntity;
// My Utils
import com.mycompany.service.MyServiceException;
@LocalClient
public class MyServiceTest extends TestCase {
private InitialContext initialContext;
@EJB
private MyService service;
@Resource
private UserTransaction userTransaction;
@PersistenceContext
private EntityManager entityManager;
protected void setUp() throws Exception {
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.openejb.client.LocalInitialContextFactory");
initialContext = new InitialContext(properties);
// Here's the fun part
initialContext.bind("inject", this);
userTransaction.begin();
try {
Query query = entityManager.createQuery("delete from MyEntity");
query.executeUpdate();
}
finally {
userTransaction.commit();
}
}
/**
* Add entity
*
* @throws Exception
*/
public void testCallAddMyEntity() throws Exception {
MyEntity myEntity = new MyEntity("arg1-1", "arg1-2");
try {
Long id = service.addMyEntity(myEntity);
assertNotNull("Call to add myEntity failed to return id", id);
}
catch (MyServiceException ex) {
fail("Call to add myEntity failed with exception");
}
}
/**
* Remove entity
*
* @throws Exception
*/
public void testCallRemoveMyEntity() throws Exception {
MyEntity myEntity = new MyEntity("arg2-1", "arg2-2");
try {
// should probably write data to database using query here, but
this is just a prototype...
Long id = service.addMyEntity(myEntity);
assertNotNull("Call to add myEntity failed to return id", id);
service.removeMyEntity(id);
// Add call to check db for proper removal
assertTrue(true);
}
catch (MyServiceException ex) {
fail("Call to add server failed with exception");
}
}
}
Ilane wrote:
>
> I am setting up some tests for existing session EJBs, basically for
> regression testing purposes, but also to run automatically during builds.
> These EJBs are essentially a CRUD interface for the persisent entities
> using Hibernate.
>
> I have the following issues I'm trying to resolve:
>
> * What is the most appropriate way to clear the database in the setUp()
> method?
>
--
View this message in context:
http://www.nabble.com/EJB-testing-with-Hibernate-%2B-Maven-%2B-JUnit-tp24705907p24729128.html
Sent from the OpenEJB User mailing list archive at Nabble.com.