在服务方法中模拟dao实例

时间:2015-07-25 12:38:42

标签: java unit-testing mocking

我有以下方法:

public List<Author> getNewsAuthors() throws ServiceException, ConnectionException {
 try {
   logger.debug("Getting the NewsDAO instance");
   NewsDAO newsDAO = daoFactory.getNewsDAO(scopingDataSource);

   logger.debug("Getting news authors from the database");
   List<Author> authorList = newsDAO.getNewsAuthors();

   logger.debug("Returning all news authors");
   return authorList;
 }
 catch (SQLException e) {
   logger.error("Error in retrieving all news authors");
   if (isConnectionException(e.getLocalizedMessage())) {
   throw new ConnectionException(e.getLocalizedMessage());
 }
  else {
    throw new ServiceException(e.getLocalizedMessage());
  }
 }
}

我可以在方法调用中模拟DAO实例吗?请注意,dao实例在构造函数中接收数据源。

我正在使用EasyMock。

1 个答案:

答案 0 :(得分:0)

你需要做这样的事情:

  1. 创建模拟DaoFactoryNewDAO,例如
  2. DaoFactory daoFactory = EasyMock.createMock(DaoFactory.class); NewsDAO newsDAO = EasyMock.createMock(NewsDAO.class);

    1. 然后在你的测试中你需要设置考试:
    2. EasyMock.expect(daoFactory.getNewsDAO(isA(ScopingDataSource.class))).andReturn(newsDAO);