Home  >  Q&A  >  body text

java - 单元测试对dao层的测试有什么好的实践方案?

比如对某个新增的dao进行单元测试,那岂不是要真的往数据库中插入一条数据?每次单元测试都新增一条数据?

还有,查询操作,返回一个List的对象集合,怎么判断数据是准确的呢?

对于单元测试,大家有什么好的实践方案吗?

阿神阿神2742 days ago501

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:58:06

    When using a database in unit testing, you can consider two options:

    1. Build a long-term test database as a unit test. Clear irrelevant data before starting or after the test is completed to ensure the repeatability of the test. The disadvantage is that unit tests may fail when multiple people run them at the same time.

    2. Use an in-memory database (such as H2). The advantage is that there is no need to clear irrelevant data. The disadvantage is that the database initialization process (such as table creation statements) must be included in the unit test. If the initialization is complex, it will also affect the efficiency of unit testing.

    As for how to verify the query results, it is basically based on business logic. For example, when my unit test runs here, the query will definitely return 27 records, so verify whether the number of returned records is 27. In other cases, you can design it yourself.

    reply
    0
  • Cancelreply