BizTalk Utilities CV ,   Jobs ,   Code library
 
Go to the front page to continue learning about XML or select below:

Contents

ReBlogger Contents

Previous posts in XML

 
 
Page 16512 of 21350

Mock JDBC driver not worth it

Blogger : Michael Slatterys Weblog
All posts : All posts by Michael Slatterys Weblog
Category : XML
Blogged date : 2005 Nov 02

I think mocking DAOs is better than mocking a JDBC driver.

A while back I wrote a blog entry that described an initial design of a JDBC driver that would be useful for mocking. It would use a cache stored in XML format. It would even support insert/update/delete (by having multiple cache 'states').

I put off writing the driver and instead used HSQLDB + DbUnit. It worked ok, but I was not satisfied with performance and the startup time of Hibernate. I was also too lazy to implement the driver I had described.

Instead I decided to mock the DAO. I already have all DAOs implement from a base interface (similar to how the Hibernate site suggests). I extended this interface to include enough query functionality to minimize Hibernate coupling.

I implemented a WrapperDao and a MemoryDao from the base interface. From this I can switch the back end from Hibernate to the MemoryDao. (The MemoryDao throws an exception for some of the more fancy methods).

Some snips of code:
interface GenericDao<T, ID>
{
  T find(ID id)
  List<T> findAll();
  List<T> findByExample(T exampleInstance);
  List<T> findByMap(Map example);
  List<T> findByProperties(Object.. namesAndValues);
  List<T> findByQueryName(String qname, Object... args);
  //yada, yada.
}

class HibernateDao<T, ID> implements GenericDao<T, ID> { /* lots o'code */ }
class MemoryDao<T, ID> extends DaoWrapper<T, ID> { /* lots o'code */ }

class DaoWrapper<T, ID> extends GenericDao<T, ID>
{
  GenericDao<T, ID> delegate;
  DaoWrapper(GenericDao<T, ID> delegate) { this.delegate = delegate; }
  T find(ID id) { return delegate.find(ID id); }
  //etc, etc.
}

class OrderDao extends DaoWrapper<Order, Long>
{
  List<Order> findByCustomer(Long custId)
  {
    //any one of the following would work:
    return findByProperties("custId", custId);

    return findByMap(Collections.singletonMap("custId", custId));

    Order example = new Order();
    example.setCustId(custId);
    return findByExample(example);
  }
}

So once I have the above, I can mock easily. I create Daos (like OrderDao) backed by MemoryDao instead of HibernateDao. I have a single class that sets this all up and it can be resued by any test. I can then run my tests against the lightening fast DAOs.

Of course there are other ways you can mock DAO objects. But the above is very easy and will even work for some functional testing, if your willing to fully implement searching in MemoryDao.


Read comments or post a reply to : Mock JDBC driver not worth it
Page 16512 of 21350

Newest posts
 

    Email TopXML