views:

124

answers:

2

Hello, I am doing tests on an ejb3-project using ejb3unit session bean test. The following test will fail with the last assertNotSame() check.

public void testSave() {
   Entity myEntity = new Entity();
   myEntity.setName("name1");
   myEntity = getBeanToTest().save(myEntity);
   assertNotSame("id should be set", 0l, myEntity.getId());
   // now the problem itself ...
   int count = getBeanToTest().findAll().size();
   assertNotSame("should find at least 1 entity", 0, count);
}

So, what is happening. The save(entity) method delivers my "persisted" object with an id set. But when I'll try to find the object using findAll() it won't deliver a single result. How can I get my ServiceBean.save method to work, so the persisted entity can be found?

Edit

My ServiceBean looks like this

 @Stateless
 @Local(IMyServiceBean.class)
 public class MyServiceBean implements IMyServiceBean {

   @PersistenceContext(unitName = "appDataBase")
   private EntityManager em;

   public Entity save(Entity entity) {
     em.merge(entity);
   }
   public List<Entity> findAll() {
     ... uses Query to find all Entities ..
   }
 }

and for ejb3unit the ejb3unit.properties:

ejb3unit_jndi.1.isSessionBean=false
ejb3unit_jndi.1.jndiName=project/MyServiceBean/local
ejb3unit_jndi.1.className=de.prj.MyServiceBean
A: 

Perhaps you don't have a running transaction, hence your entity isn't saved.

One option is to manually start the transaction by injecting a @PersistenceContext in the test, but better look for automatic transaction management in ejb3unit.

Bozho
might there be a problem using: @PersistenceContext(unitName = "appDataBase")?
justastefan
rather not. did you check whether you have a running transaction?
Bozho
gave you no plus, because, that actually was the problem (sry, could give you plus, because my reputation sucks :-/ )
justastefan
@justastefan - if my answer solved the problem, you can click the tick below the votes - it's for accepting answers.
Bozho
+1  A: 

Here we go..

public void testSave() {
  Entity myEntity = .. // create some valid Instance
  // ...
  EntityTransaction tx = this.getEntityManager().getTransaction();
  try {
    tx.begin();
    myEntity = getBeanToTest().save(myEntity);
    tx.commit();
  } catch (Exception e) {
    tx.rollback();
    fail("saving failed");
  }
  // ...
}

maybe this'll help some of you.

justastefan