Unit Test Practice

Source: Internet
Author: User
Tags assert
Requirements for testing:
Test the DAO operations and service for one account.
Java code//First test the most basic DAO bar package Org.wuhua.dao;      Import java.util.Collection;       Public interface Ibasedao {Object Save (object o);       void Delete (Object o);       Object Update (object o);   Collection list (); According to my understanding, the other side of the test is to be separated from the mock object, (at first I always thought you wanted to mock the object is you want to test the thing, engage in, I am very confused. )。 All you have to do now is to see what your Ibasedao is accomplishing. If the implementation is using springhibernatetemplate then you mock an object like this, but this object is not an interface, so you need to use the Easymock extension package to support it. If you achieve the use of pure hibernate words. Then you're going to mock a sessionfactory. It's simple, is that what we call decoupling? I think yes, that's decoupling. Ha ha

Take a look at my implementation, using the spring implementation.
Java code   package org.wuhua.dao.impl;      import java.util.collection;       import org.springframework.orm.hibernate3.support.hibernatedaosupport;   import org.wuhua.dao.ibasedao;      public class basedao extends   HibernateDaoSupport   implements ibasedao {           public void delete (Object o)  {             this.gethibernatetemplate (). Delete (o);              }          public collection list ()  {                    return  null;       }          public object& nbSp;save (Object o)  {           return  This.gethibernatetemplate (). Save (o);                     }          public Object  Update (Object o)  {            This.gethibernatetemplate (). Update (o);           return  o;       }     }   test Code
Java code   package org.wuhua.dao;      import java.io.serializable;      import junit.framework.testcase;      import org.easymock.mockcontrol;    import org.easymock.classextension.mockclasscontrol;   import  org.springframework.orm.hibernate3.hibernatetemplate;   import org.wuhua.dao.impl.basedao;       public class basedaotest extends testcase {          MockControl control;          private  hibernatetemplate ht;          private BaseDao baseDao;           protected void setup ()  throws exception  {           control =  Mockclasscontrol.createcontrol (HiBernatetemplate.class);           ht =  ( hibernatetemplate)  control.getmock ();           basedao  = new basedao ();            Basedao.sethibernatetemplate (HT);       }           public void testsave ()  {            object o = new object ();            Ht.save (o); 
I have a question here.         1, why Hibernatetemplate return is serializable. 2, set the return plant why must be consistent with the call Ht.save (O).
        control.setreturnvalue (New wuhua ());            control.replay ();            basedao.save (o);           control.verify ();        }               Public void testupdate ()  {           object  a = new object ();           ht.update (a) ;                    Control.replay ();           try {                basedao.update (a);          &Nbsp;     fail ("not catch exception!");            } catch (exception e)  {                            }           control.verify ();        }               class wuhua implements serializable {}     }  

It's the first time I've taken a very serious test, and there's a lot of things I don't understand.

There is no sense in the test service, for the test DAO layer, each has its own view of the performance.
Like what
Robbin elder brother suggested:

Testing DAO is better than testing it with a database. Because the DAO test is not intended to be a DAO interface implementation right, it is testing whether the SQL is sent as you expect, as you expected to return the result set. This time you mock, the test is meaningless.

Hyysguyang elder brother suggested: The article Wuhua writes the stratification reason many. Here, my opinion is one-sided.
But it's good for a mock.
For example, when the service test can completely isolate the database,

What I'm saying now is,
Even the service can isolate the DAO layer, which means that the DAO layer is also able to isolate related data implementations. You can also mock an object. Instead of using the actual connection instead. If our logic is not wrong, the test is passed, as for the data layer detection, it is not our business, such as hibernate by Hibernate to test, spring from spring to test,oracle by its own to do. Do your own thing, don't go into other muddy waters. Isn't that a lot of cool?

But the test of the database is special after all, remember the purpose of the test is to ensure that your code quality, if you are sure that your test will be no problem, there is nothing to say, or as much as possible test.
In fact, the most original unit test (plain testcase) is used to measure the method, measuring the business logic, if the logic of the test, no logic is not measured, the same reason, I believe you will not test a bean's Get/set method.
Remember the purpose and motivation of your test, if you think that testing the DAO layer is to test your logic (you're sure that your DAO's implementation code is really logical), then you mock it, but we're more convinced that we're measuring the DAO layer, which is more about accessing the database, you're connected, SQL is correct, sequence is correct and so on, and these you have to really connect the database, and therefore, we generally are directly access to the database to test, of course, if possible you can use the memory library.
In fact, our testing of DAO is generally done in so-called integrated unit tests. I think you should determine your test strategy and then use the appropriate test methods. I am in the current development is to use such a way to measure.

The above two eldest brother all suggest to test DAO's time or connection database is good.
But the individual thinks the unit test of the top two eldest brother is not pure unit test, but integration unit test.
In fact, the test of this thing is just for the project better, faster completion. As for whether pure units, or integrated unit testing, to see your needs, if you think the integration unit test to help the project, then use it, now found there is no obvious boundaries.


Ignore it, now return to our user registration example.
Java code 1.     Public interface Iaccountdao extends Ibasedao {2.     Public account Findaccountbyid (String ID);     3. Public account Findaccounbyname (String name); 4.}


Actual implementation Code
Java code   package org.wuhua.dao.impl;      import java.util.list;      import org.wuhua.dao.iaccountdao;   import org.wuhua.model.account;      public class accountdao extends basedao implements iaccountdao  {     Public account findaccountbyid (string id)  {            return  [Account]  this.gethibernatetemplate (). Get (Account.class,  id)  ;       }          public  account findaccounbyname (string name)  {            list l = this.gethibernatetemplate (). Find ("from account as a  Where a.name=? ",  name);           if (l !=  null&Nbsp;&& l.size ()  >=1)                 return  (account)  l.get (0);            else                return  null;       }  }  


Java code   package org.wuhua.dao;      import java.util.arraylist;   import java.util.list;      import junit.framework.assert;   import  junit.framework.testcase;      import org.easymock.mockcontrol;   import  org.easymock.classextension.mockclasscontrol;   import  org.springframework.orm.hibernate3.hibernatetemplate;   import org.wuhua.dao.impl.accountdao;    import org.wuhua.model.account;             Public  class AccountDaoTest extends TestCase {               private AccountDao accountDao;        private org.springframework.orm.hibernate3.hibernatetemplate ht;        Private mockcontrol control;          protected void setup ()  throws exception {            control = mockclasscontrol.createcontrol (Hibernatetemplate.class);           ht =  ( hibernatetemplate)  control.getmock ();            Accountdao = new accountdao ();            Accountdao.sethibernatetemplate (HT);       }           protected void teardown ()  throws Exception {                    }               public void testfindaccountbyid () {            account a = new account ("Wuhua");            a.setid ("ten");                          ht.get (Account.class, a.getid ());                       Control.setreturnvalue (a);                       control.replay ();                       Account result =    Accountdao.findaccountbyid (A.getid ());                      assertnotnull (Result);          &nbSp;    assert.assertequals (A.getid (), Result.getid ());            assert.assertequals (a, result);                       control.verify ();                   }               public void testfindaccountbyname () {            account a = new account ("Wuhua");                             ht.find ("From account as a where a.name=?",  A.getname ());           List l = new  ArrayList ();          l.add (a);            control.setreturnvalue (l);                      control.replay ();                       Account result =   accountdao.findaccounbyname (A.getname ());               assert.assertequals (A.getid (), Result.getid ());            assert.assertequals (a, result);                       control.verify ();                   }  }  

Test service because of the DAO that the service relies on, so just mock a DAO. Here I have a detailed introduction to the test for registering this feature
Java code   Public interface iaccountservice extends ibaseservice  {         account findaccountbyid (string id);          account findaccounbyname (string name);          void regist (Account account)  throws ObjectExistsException;   }  

The implementation of the registration function. Java code public void Regist throws objectexistsexception {if accountdao.findaccounbyname.              GetName ())!= null) throw new Objectexistsexception ("User ' s name is exists!");   Accountdao.save (account); }


Test Code Java Code       PROTECTED VOID SETUP ()  throws exception {            control = mockcontrol.createcontrol ( Iaccountdao.class);           accountDao =  ( Iaccountdao)  control.getmock ();           as =  new accountservice ();           as.setaccountdao ( Accountdao);       }         public void  Testfindaccountbyname ()  {           string name  =  "Wuhua";           accountdao.findaccounbyname ( Name);           account a = new account ( "Wuhua");   &NBsp;       a.setid (name);            control.setreturnvalue (a);            Control.replay ();           Account at =  As.findaccounbyname (name);           assert.assertequals (name ,  at.getid ();        &

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.