The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

tedyoung (12) [Avatar] Offline
#1
I'd like to see a higher-level discussion of testing with a persistence layer (e.g., Hibernate). For example, what should I test to make sure my DAOs work properly? How do I separate the testing of the db/persistence layer from the testing of the domain layer? How do we/can we use annotations to specify the target database to test (might need to discuss dependency injection, though).

;ted
felipe.leme (18) [Avatar] Offline
#2
Re: DB/Persistence Unit Testing
Hi Ted,

> I'd like to see a higher-level discussion of testing with a persistence layer (e.g., Hibernate).

Ok, let me answer some of your questions, and hopefully that could start such discussion.

> For example, what should I test to make sure my DAOs work properly?

Typically, I like to write a couple of tests for each method, specially in methods that load something from the database. I write separate tests for negative scenarios (like searching for an object that does not exist, or searching in an empty database), positive scenarios (searching when just one row matches it, or many rows match; many times testing for just 1 row is not enough, as you might have omit a 'select distinct' in the query), eager fetching on lazy relationships, etc. Chapter 18 examples cover all of these scenarios.

> do I separate the testing of the db/persistence layer from the testing of the domain layer?

I like to do so, replacing the persistent layer by mocks. Chapter 18 also has a sub-section about it. But it is still important to write integration tests that exercises these 2 layers working together (although you don't need to add as much integration tests as unit tests).

> How do we/can we use annotations to specify the target database to test (might need to discuss
> dependency injection, though).

I am not aware of any framework that uses annotations for such purpose, and to be honest, I don't think that would be a good idea, as annotations are more convenient to configure settings that don't change. I think the database is better configured in a properties or XML file, so it could be switched at runtime. And switching it is particularly important when you use ORM, so you can run the unit tests on a fast embedded database while developing, and in the target database at official and nightly builds.

-- Felipe