简体   繁体   中英

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. 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. 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:

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. And probably this would also happen with other DB such as MySQL.

So what's the point in using a h2 database in this case? 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.

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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