users@glassfish.java.net

Re: JUnit tests with Glassfish EJB's

From: <glassfish_at_javadesktop.org>
Date: Tue, 23 Mar 2010 03:53:34 PDT

I've done a simple test project to inspect this and the results a rather interesting.

[code]
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class AnBean {
    
    @PersistenceContext(unitName="testPU")
    private EntityManager em;

    public void addAnEntity(String someData) {

        AnEntity e = new AnEntity();
        e.setSomeData(someData);
        em.persist(e);
    }

    public AnEntity getAnEntity(String someData) {

        Query q = em.createNamedQuery("AnQuery");
        q.setParameter("data", someData);
        return (AnEntity) q.getSingleResult();
    }
}
[/code]

[code]
@Entity
@NamedQuery(name="AnQuery", query="select e from AnEntity e where e.someData = :data")
public class AnEntity implements Serializable {

    @Id
    @GeneratedValue
    private Long id;
    private String someData;

    public String getSomeData() {
        return someData;
    }

    public void setSomeData(String someData) {
        this.someData = someData;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}
[/code]

[code]
public class AnBeanTest {

    static EJBContainer ejbCon;

    private AnBean bean;

    @Before
    public void initEjb() throws Exception {
        ejbCon = EJBContainer.createEJBContainer();
        Context ctx = ejbCon.getContext();
        bean = (AnBean) ctx.lookup("java:global/classes/AnBean");
    }

    @Test
    public void beanTestA() { //this one is successfull

        bean.addAnEntity("xxx");
        bean.getAnEntity("xxx");
    }

    @Test
    public void beanTestB() { //this one faild

        bean.addAnEntity("xxx");
        bean.getAnEntity("xxx");
    }

    @After
    public void closeEjb() {
        bean = null;
        ejbCon.close();
    }
}
[/code]

Test A is successful and the exactly same test B fails.

Please tell me is there something wrong in my After and Before methods ?
Or is this a bug ?
[Message sent by forum member 'walec51']

http://forums.java.net/jive/thread.jspa?messageID=393281