views:

271

answers:

2

Currently we are testing out entity classes and "worker" classes by writing java servlets for each entity and doing Insert,update,delete,find... for each entity to ensure that it works. The worker classes are simply implementations of an interface that persists the entity to the database using JDBC, they do the DB work for the entity.

What I'm wondering is, what is the best way to test entity classes in Java?

I'm looking for an automated approach rather than writing, basically, a mock application that calls all of the functions that I'm trying to test for each new entity that is created.

A: 

One option would be to use reflection to find the different pieces of the entities (i.e. different fields) and then have the method call save, update, delete, etc using those different entities. Then, when you added a new entity, if your setup is done using xml or something similar, the test will just pick them up.

I am speaking from a Hibernate user perspective, so this may not be entirely applicable to your situation, but it has worked well for me in the past.

aperkins
Can you clarify the "using reflection" part? How would that help in determining what values to populate entities with? Especially since some (majority?) of them may have constraints expressed at application and / or database level.
ChssPly76
So, in hibernate we have annotations on the classes that help to keep track of that information, something like @column(length=50) to notify us that the longest that VARCHAR can be is 50. We also have some standards, like to not do strange validation in the database (i.e. bizarre, non-standard constraints). You can find the type of each field, and then use that to generate a value. If the field is itself an entity, you can either attach an existing one from the database or create a new one (as appropriate - i.e. many-to-one vs many-to-many relationship)
aperkins
Fair enough. I have to say, though, that it sounds like you're testing Hibernate Validator as much (or more so) as your DAOs :-)
ChssPly76
True, I am more checking that the DAOs are properly setup for usage with our database and the persistence layer than anything. I am also checking the DTOs as well in this case, and making sure they are mapped appropriately.
aperkins
+1  A: 

You should be able to set-up and use entity and "worker" (as you put it) classes independently or servlets and a Web container.

With pure JDBC and JUnit, you would typically do the following:

  1. Open a JDBC connection in TestCase constructor.
  2. Begin a transaction on setUp().
  3. Rollback a transaction on tearDown().
  4. Use the actual entity instances in the particular testXxx() methods.

In this approach, you would be having one, possibly local, database instance per developer. For something more advanced, consider DbUnit.

javashlook