Chapter 26. Testing Seam applications
Both kinds of tests are very easy to write.
26.1. Unit testing Seam components
All Seam components are POJOs. This is a great place to start if you want easy unit testing. And since Seam emphasises the use of bijection for inter-component interactions and access to contextual objects, it's very easy to test a Seam component outside of its normal runtime environment.
Consider the following Seam component:
@Stateless
@Scope(EVENT)
@Name("register")
public class RegisterAction implements Register
{
private User user;
private EntityManager em;
@In
public void setUser(User user) {
this.user = user;
}
@PersistenceContext
public void setBookingDatabase(EntityManager em) {
this.em = em;
}
public String register()
{
List existing = em.createQuery("select username from User where username=:username")
.setParameter("username", user.getUsername())
.getResultList();
if (existing.size()==0)
{
em.persist(user);
return "success";
}
else
{
return null;
}
}
}
We could write a TestNG test for this component as follows:
public class RegisterActionTest
{
@Test
public testRegisterAction()
{
EntityManager em = getEntityManagerFactory().createEntityManager();
em.getTransaction().begin();
User gavin = new User();
gavin.setName("Gavin King");
gavin.setUserName("1ovthafew");
gavin.setPassword("secret");
RegisterAction action = new RegisterAction();
action.setUser(gavin);
action.setBookingDatabase(em);
assert "success".equals( action.register() );
em.getTransaction().commit();
em.close();
}
private EntityManagerFactory emf;
public EntityManagerFactory getEntityManagerFactory()
{
return emf;
}
@Configuration(beforeTestClass=true)
public void init()
{
emf = Persistence.createEntityManagerFactory("myResourceLocalEntityManager");
}
@Configuration(afterTestClass=true)
public void destroy()
{
emf.close();
}
}
Seam components don't usually depend directly upon container infrastructure, so most unit testing as as easy as that!