简体   繁体   English

使用H2数据库进行单元测试DAO层

[英]Unit testing DAO layer with H2 database

After a lot of reading in internet, i found out that it seems to be a good practice to use a in-memory DB like H2 to unit test the DAO layer. 在互联网上大量阅读之后,我发现使用内存数据库(如H2)来对DAO层进行单元测试似乎是一个好习惯。 The idea behind is to avoid working with the production DB. 背后的想法是避免使用生产数据库。

Fine, so I set up a H2 DB and activated the H2 PostgreSQL Compatibility Mode, since my production DB is on Postgres. 很好,所以我建立了一个H2数据库并激活了H2 PostgreSQL兼容模式,因为我的生产数据库位于Postgres上。 The problem I'm now facing: when I run on H2 the original SQL queries in order to build the test DB, this query is not accepted as valid by H2: 我现在面临的问题:当我在H2上运行原始SQL查询以构建测试数据库时,H2不接受此查询为有效查询:

ALTER SEQUENCE MYERP.ecriture_comptable_id_seq OWNED BY MYERP.ecriture_comptable.id;

I guess that using the PostgreSQL Compatibility Mode is not a guarantee that all the Postgres specific syntax will be accepted by H2. 我猜想使用PostgreSQL兼容模式并不能保证H2会接受所有特定于Postgres的语法。 And probably this would also happen with other DB such as MySQL. 而且,其他数据库(例如MySQL)也可能会发生这种情况。

So what's the point in using a h2 database in this case? 那么在这种情况下使用h2数据库有什么意义呢? Did I miss something? 我错过了什么?

Unit testing should focus on testing a unit. 单元测试应重点测试单元。 PostgreSQL is external to your application and thus trivially not part of any DAO that uses it: no 'unit test' should be written that uses any such external database. PostgreSQL在您的应用程序外部,因此不属于使用它的任何DAO的一部分:不应编写使用任何此类外部数据库的“单元测试”。

Using the database for integration tests may be fine but as you already noticed multiple problems may arise when you use a different database to execute your integration tests (I know very little applications that only use ANSI-SQL without any triggers or other vendor specific SQL extensions like UPSERT in PostgreSQLs case or the SQL in your post). 使用数据库进行集成测试可能会很好,但正如您已经注意到的那样,当您使用其他数据库执行集成测试时可能会出现多个问题(我知道很少有仅使用ANSI-SQL而没有任何触发器或其他特定于供应商的SQL扩展的应用程序例如PostgreSQL中的UPSERT或您帖子中的SQL)。

So what if your production base is in-memory too? 那么,如果您的生产基地也在内存中怎么办? That's quite difficult and I would argue an integration test would be fine, just don't call it unit test. 这非常困难,我认为集成测试会很好,只是不要将其称为单元测试。 All of this just highlights the pain points of doing business logic in your database (eg through triggers that you now can't test) or using vendor specific sql which has several advantages that don't play so well with changing the underlying database vendor. 所有这些都凸显了在数据库中进行业务逻辑的痛点(例如,通过现在无法测试的触发器)或使用特定于供应商的sql的痛点,这些优势在更改基础数据库供应商时无法发挥很好的作用。

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

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