Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unit test jdbc code in java? [closed]

I'd like to write some unit tests for some code that connects to a database, runs one or more queries, and then processes the results. (Without actually using a database)

Another developer here wrote our own DataSource, Connection, Statement, PreparedStatement, and ResultSet implementation that will return the corresponding objects based on an xml configuration file. (we could use the bogus datasource and just run tests against the result sets it returns).

Are we reinventing the wheel here? Does something like this exist already for unit testing? Are there other / better ways to test jdbc code?

like image 447
ScArcher2 Avatar asked Nov 05 '08 19:11

ScArcher2


People also ask

How do you test for JdbcTemplate?

There are two ways to unit test methods that use JdbcTemplate. We can use an in-memory database such as the H2 database as the data source for testing. However, in real-world applications, the SQL query could have complicated relationships, and we need to create complex setup scripts to test the SQL statements.


1 Answers

You have several options:

  • Mock the database with a Mock library, e.g. JMock. The huge drawback of this that your queries and the data will most likely be not tested at all.
  • Use a light weight database for the tests, such as HSQLDB. If your queries are simple, this is probably the easiest way to go.
  • Dedicate a database for the tests. DBUnit is a good option, or if you are using Maven, you can also use the sql-maven-plugin to set up and tear down the database properly (be careful of dependencies between tests). I recommend this option as it will give you the biggest confidence that the queries work properly with your db vendor.

Sometimes it is necessary and useful to make these tests configurable so that these tests are only executed if the database is available. This can be done with e.g. build properties.

like image 82
Tatu Lahtela Avatar answered Oct 08 '22 10:10

Tatu Lahtela