简体   繁体   中英

Testing Java database entity classes

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.

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 .

One option would be to use reflection to find the different pieces of the entities (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM