【问题标题】:EJB3Unit save-function doesn't really save my entityEJB3Unit 保存功能并没有真正保存我的实体
【发布时间】:2010-02-11 16:50:03
【问题描述】:

我正在使用ejb3unit session bean test 对 ejb3 项目进行测试。以下测试将因最后一次assertNotSame() 检查而失败。

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

那么,发生了什么。 save(entity) 方法提供了我的“持久”对象,并设置了一个 id。但是当我尝试使用findAll() 查找对象时,它不会提供一个结果。如何让我的 ServiceBean.save 方法工作,以便可以找到持久化的实体?

编辑

我的 ServiceBean 看起来像这样

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

对于 ejb3unit,ejb3unit.properties:

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

【问题讨论】:

    标签: java unit-testing ejb-3.0 testing


    【解决方案1】:

    我们开始..

    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");
      }
      // ...
    }
    

    也许这会对你们中的一些人有所帮助。

    【讨论】:

      【解决方案2】:

      也许您没有正在运行的事务,因此您的实体没有保存。

      一种选择是通过在测试中注入@PersistenceContext 来手动启动事务,但最好在 ejb3unit 中寻找自动事务管理。

      【讨论】:

      • 使用@PersistenceContext(unitName = "appDataBase") 会不会有问题?
      • 而不是。你检查过你是否有一个正在运行的事务吗?
      猜你喜欢
      • 2017-02-11
      • 1970-01-01
      • 2022-07-29
      • 1970-01-01
      • 2016-11-16
      • 2018-08-21
      • 1970-01-01
      • 2022-01-20
      • 2017-05-11
      相关资源
      最近更新 更多