Hi i need some help, how to unit test a DAO?
here my code:

@Transactional
public class ProjectDaoImpl extends HibernateDaoSupport implements ProjectDao {

    Log logger = LogFactory.getLog(this.getClass());
    private String message;

    /**
     * {@inheritDoc}
     */
    public List<User> retrieveAll() {
        return this.getHibernateTemplate().loadAll(User.class);
    }

    /**
     * {@inheritDoc}
     */
    public boolean saveOrUpdateUser(User user) {
        boolean res = false;
        try {
            this.getHibernateTemplate().saveOrUpdate(user);
            res = true;
        } catch (DataAccessException e) {
            res = false;
            this.logger.error("DataAccessException", e);
        }
        return res;
    }

    /**
     * {@inheritDoc}
     */

    @SuppressWarnings("unchecked")
    public User retrieveUserById(Long id) {
        User user = null;
        DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
        Criterion criterion = Restrictions.eq("user_id", id);
        criteria.add(criterion);
        try {
            List<User> users = this.getHibernateTemplate().findByCriteria(criteria);
            if (users != null && users.size() > 0)              user = users.get(0);
        } catch (DataAccessException e) {
            this.logger.error("DataAccessException", e);
        }

        return user;
    } 



/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
public List<User> retrieveUserByCriteria(DetachedCriteria criteria) {
    List<User> users = null;
    try {
        users = this.getHibernateTemplate().findByCriteria(criteria);
    } catch (DataAccessException e) {
        this.logger.error("DataAccessException", e);
    }
    return users;
}

/**
 * {@inheritDoc}
 */
public boolean deleteUser(User user) {
    boolean res = false;
    try {
        this.getHibernateTemplate().delete(user);
        res = true;
    } catch (DataAccessException e) {
        this.logger.error("DataAccessException", e);
    }
    return res;
}

}

... write unit tests for them and run them.
since I don't know what your expected outcome should be, can't really help you much.

but, for adding:

  1. test if the nr of elements is increased by one
  2. verify your new element is in your list

for deleting:

  1. verify the element is in the list
  2. verify that after the delete there is one element less
  3. verify that your object is no longer in the list

...

Actually I have an interface UserDao, then UserDaoImpl which implement the interface. and now i need to do unit testing on UserDaoImpl. These methods are communicating directly to the database. will it be the same? I can't even create an instance of the class UserDaoImpl. Why this issue?

Edited 3 Years Ago by techyworld

This article has been dead for over six months. Start a new discussion instead.