Sara
Sara

Reputation: 2505

Testing methods which query database with JUnit

How should I unit test methods which their intent is querying the database and return some data? For other situations I can just mock the objects but in this case which I want to test whether they return the correct data, how should I check it isolated from db? Should I use some kind of special db? But then how should I configure that new db to work like the other one with all those columns, etc?

Thanks.

Update: Thanks to everyone, their responses leaded me to the correct path. I finally used debry. I just added a new persistence.xml for that. No other significant changes and it seems to be working now.

Upvotes: 2

Views: 2587

Answers (3)

Garrett Hall
Garrett Hall

Reputation: 30022

The question is what behavior do you need to unit test? If you mocked out the database then you've tested all the important logic. Your database adapter will either work or not work, which you can verify in integration/acceptance tests against a real database.

Upvotes: 1

nkukhar
nkukhar

Reputation: 2025

You can use DBUnit. It takes your current schema and you can easily mock your data.

Upvotes: 1

DeejUK
DeejUK

Reputation: 13471

One approach I've used with great success is to use:

  1. Maven to build your project
  2. Liquibase (or Flyway) to manage your database schema, and versioning it
  3. H2 as an in-memory database that is started along with your tests.

There's a fair bit to learn there if you haven't used any of the above, but in my experience it was well worth it. This worked really well with a Spring application; with other setups your mileage may vary.

Maven should start an instance of the H2 database in-memory before doing any tests. In a Spring application, you can just specify your datasource with an H2 JDBC URL and it'll start automagically.

You can use Liquibase to run a set of XML scripts to set up your database schema, and then a separate file to populate them with test data (either by specifying different files when running Liquibase, or by using the context attribute of each changeSet). This can be done with Maven, or in Spring using a specific Liquibase bean.

From there you can test your application exactly as if it was a normal app. No need for mocking, and you get much more useful tests as a result. You may need to change your schema or otherwise work around SQL differences between H2 and your native RDBMS.

As an aside, I'm greatly in favour of these sorts of tests. In my experience mocking everything doesn't really gain you any interesting insights, and should be a last resort for when intra-build integration tests aren't possible. There are many that disagree with me though!

Upvotes: 3

Related Questions