JUnit tests using a mock database

2019-08-17 01:07发布

问题:

I am developping an application that tests different WebServices, and I want it to be as generic as possible. I need to populate database to do JUnit tests, but I don't want these changes to be commited. I know that some in-memory databases like HSQL DB allow testing on a sort of a virtual (or mock) database, but unfortunately I use oracle and I cannot change it now because of my complex data tables structure.

What is the best practice you suggest? Thanks.

回答1:

First of all, HSQL and Hibernate aren't related in any way. The question is whether you can find an embedded database which supports the same SQL as your production database (or rather the subset of SQL which your application uses).

A good candidate for this is H2 database since it emulates a lot of different SQL flavours.

On top of that: Don't test the database. Assume that the database is tested thoroughly by your vendor and just works.

In my code, I aim for:

  1. Save and load each entity.

  2. Generate the SQL for all the queries that I use and compare them against String literals in tests (i.e. I don't run the queries against the database all the time).

  3. Some tests look for a System property. If it's set, then they will run the queries against the database. This happens during the night on my CI server.

The rationale for this: As long as the DB schema doesn't change, there is no point to actually run the queries. That means running them during the day while I sit in front of the computer is a huge waste of time.

To make sure that "low impact" changes don't slip through the gaps, I let a computer run them when I don't care.

Along the same lines, I have mocks for many DAOs which return various predefined results, so I don't have to query the database. The rationale here is that I want to test the processing of results from the database, not the JDBC API, the DB driver, the OS's TCP/IP stack, the network hardware (and software), or any other of the 1000 things between my code and the database records on a harddisk somewhere.

More details in my blog: http://blog.pdark.de/2008/07/26/testing-with-databases/