Situation:
The private field id (primary key of DB) ist set by the
JEE container and JPA. For this reason no public setter for id shall exist.
To set the id for
JUnit tests, reflection is used. To make it a little bit more complicated a class employee inherits from the super class Person. The id field exist in the Person class only.
The following code snippet from JUnit
test class works:
Employee empl = new Employee();
try {
// access private field id and set a unique id otherwise set by DB through container
Person pers = new Person(); //ugly workaround, but it works, create dummy super class!
// inherited declared fields are not accessible but:
Field id = pers.getClass().getDeclaredField("id"); // get id ref from super class Person
id.setAccessible(true);
id.setLong(empl, Long.valueOf(i + 1)); // use id ref on employee!
id.setAccessible(false);
} catch (Exception e) {
//handle it
}
Questions:
1.) Though it works, it looks so weird to me, I suspect rather a bug than a feature!
2.) How to do it the clean way?
3.) Who can tell me more about this.
Any background information is welcome.
Cheers Maurice