Feasible to start writing unit test in an old project?

自古美人都是妖i 提交于 2020-01-17 12:13:24

问题


I would like to start writing unit test (JUnit) for our project. This uses J2EE 1.4 with Hibernate 3.1 and there is a tight coupling between connection code and service layer(servlets if I am right? correct me!).

So suppose I have functionality to persist some form values. The structure is something like,

MyServlet.java

public void doGet(ServletRequest request, ServletResponse response)
{
    T_Donation instance - new T_Donation();

    instance.setName(request.getParameter("name"));
    instance.setAmount(request.getParameter("amount"));

    MyDAO dao = new MyDAO();
    Boolean b = dao.persistInstance(instance);

    if(b.booleanValue())
    {
        // forward to .jsp file by means of RequestDispatcher
    } 

}

Model T_Donation

public class T_Donation implements Serializable
{
   private String name;
   private String amount;

   // getters, setters
   // equals, hashcode
}

DAO class

public class MyDAO
{
    public boolean persistInstance(T_Donation instance)
    {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null; 
        try
        {
           tx = sesion.beginTransation();
           // setters again if needed
           session.save(instance);           
           tx.commit();
        }
        catch(Exception ex)
        {
             ex.printStackTrace();
             return false;
        } 
        finally
        {
             session.close();
        }
        return true; 
    }

}

This is how the codebase is. I am learning DAO pattern and I think that too is wrongly implemented here.

So my question is, considering this small functionality, how would I start writing Unit test? And how many it would require? The first steps are really hard for me.

Also, comments about cleaner code practice are welcome.


回答1:


You can mock objects like the session by returning a mock Session from this the return of this line of code :

HibernateUtil.getSessionFactory().openSession();

Depending on how HibernateUtil is implemented, you can either have the util return a mock SessionFactory if there is a setter (or you can add one) and set it in your tests.

HibernateUtil.setSessionFactory(SessionFactory instance);

If you don't have a setter and can't modify the code, then you can use something like Powermock which will allow you to mock static methods and constructors.

That's where I would start anyway...



来源:https://stackoverflow.com/questions/18578581/feasible-to-start-writing-unit-test-in-an-old-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!