views:

128

answers:

1

I have a class with a primary key that is stored in a database. When creating a new instance of the class it can either be fetched from the HSQLDB database or for items not in the database it inserts everything but the primary key and this is autogenerated and returned to the class to set the id attribute. I then have a getID() method to retrieve this ID.

I am trying to write a JUnit test that checks to ensure the generated ID is what is returned by the getID() method but I have already used 'CALL IDENTITY' query to retrieve the ID inside the constructor and subsequent uses of this return 0. What is the best way of ensuring the generated ID is the same as the id returned by the getID() method?

+1  A: 

I would really consider the different design to to test the classes. Accessing a database really isn't a unit test in most cases. If the db ID generator works and has a test then you shouldn't really need it to test your class.

Provided that you class can return an Id then all that should matter it that your class returns the id that was put into it in at the right time.

Preet Sangha
I'm more trying to test the getID() method of the class. It just so happens this ID is generated by the database so I cannot simply check it is what I told it to be instantiated to.
Haegin
@Haegin - personally I don't explicitly test getters. I try to test behavior (which may be visible via a getter). If all your `getID()` is doing it returning a `private` field then the test isn't really worth writing, imho and the behavior of your system certainly shouldn't depend on objects having been persisted.
Nick Holt