I am starting with unit tests using Hibernate and I´ve some question about the right strategy to proceed this tests. At first I researched mock objects and stubs, then I realized that I could instantiate a Hibernate session and access my database, like the code below:
The Test Class
Code:
public class UserDAOHibernateTest extends TestCase{
UserDAO uDAO;
User u;
Session session;
@Before
public void setUp() throws Exception {
session = HibernateUtil.getSessionFactory().getCurrentSession();
uDAO = DAOFactory.instance(DAOFactory.HIBERNATE).getUserDAO();
session.beginTransaction();
u = new User();
u.setId("22222222222");
u.setSenha("7560181bc399878837802c283a2d1dbd");
u.setEmail("username@gmail.com");
session.saveOrUpdate(u);
}
@After
public void tearDown() throws Exception {
session.delete(u);
session.getTransaction().commit();
}
@Test
public void testAuthenticateUser() {
User test1 = uDAO.authenticateUser(u.getId(),u.getPassword());
assertNotNull("User not found in DB",test1);
//assertTrue(test1.equals(u));
assertSame(test1, u);
}
The Class to Be Tested
Code:
public class UserDAOHibernate
extends GenericHibernateDAO<User, Integer>
implements UserDAO {
public User autenticaUsuario(String id, String password) {
Criteria crit = getSession().createCriteria(getPersistentClass());
crit.add(eq("id",id));
crit.add(eq("password",password));
return (User) crit.uniqueResult();
}
I dont know if this kind of test code is apropriated. How is the best way to do it?
thanks[/quote]