简体   繁体   English

如何在没有ORM的情况下对DAO进行单元测试

[英]How to unit test DAOs without ORM

I am writing a JAX-RS web service right now. 我现在正在编写JAX-RS Web服务。 My database logic has been compartmentalized into DAO interfaces (eg interface ItemDAO and concrete implementation class JDBCItemDAO ), which are injected into my controllers via Dependency Injection. 我的数据库逻辑已经划分为DAO接口(例如, interface ItemDAO和具体的实现class JDBCItemDAO ),这些interface ItemDAO通过“依赖注入”注入到我的控制器中。 Right now, it is relatively simple to unit test my controllers by giving them mock DAOs. 现在,通过给我的控制器模拟DAO来对它们进行单元测试是相对简单的。 However, I can not really test my DAOs because they use the JDBC API, and don't have any dependencies, other than a ConnectionFactory (returns java.sql.Connection to callers). 但是,我不能真正测试我的DAO,因为它们使用JDBC API,除了ConnectionFactory (将java.sql.Connection返回给调用者)之外,没有任何依赖关系。 I can't really just pass a mock Connection to the DAO because just verifying the SQL query that was in the DAO isn't enough. 我真的不能仅仅将模拟连接传递给DAO,因为仅验证DAO中的SQL查询是不够的。 I want to be able to test that it works in the database. 我希望能够测试它是否可以在数据库中工作。 How can I achieve this? 我该如何实现?

  1. Set up a database. 设置数据库。 If you write standard SQL without depending on database-specific features you can use an in-memory database like H2 . 如果编写标准SQL而不依赖于特定于数据库的功能,则可以使用内存数据库,例如H2
  2. Set up DataSource object pointing to your database. 设置指向数据库的DataSource对象。 This is preferable to ConnectionFactory you have right now in DAOs. 这比您现在在DAO中拥有的ConnectionFactory更可取。 You don't want to establish new physical connections all the time as this is expensive. 您不想一直都建立新的物理连接,因为这很昂贵。
  3. Use a pooled DataSource in your production code eg HikariCP and maybe use something simplier in your test code eg SingleConnectionDataSource 在生产代码(例如HikariCP)中使用池化的DataSource ,并在测试代码(例如SingleConnectionDataSource)中使用更简单的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM