I often come across situations were I want to save the content of a large object graph (run-time or during debugging) to a set of statements recreating this object graph. This can then be used as test data in unit test cases.
Taken that leafs of the object graph are standard types (String
, BigDecimal
, Date
, etc) and the branches follow the bean convention (getters, setters, empty constructor), it should be possible to generate this kind of file (e.g. TestData.java):
public static Car createCar() {
Wheel wheel1 = new Wheel();
wheel1.setTypePressure( 2.1f );
Wheel wheel2 = new Wheel();
wheel2.setTypePressure( 2.3f );
Wheel wheel3 = new Wheel();
wheel3.setTypePressure( 2.0f );
Wheel wheel4 = new Wheel();
wheel4.setTypePressure( 2.8f );
List<Wheel> wheels = new ArrayList<>( Arrays.asList( wheel1, wheel2, wheel3, wheel4 ) );
Brake brake = new Brake();
brake.setBrakeType( BrakeType.PLAIN );
Car car = new Car();
car.setBrake( brake );
car.setWheels( wheels );
car.setColor( "blue" );
return car;
}
It would be really great to plug this directly into a debug session somehow, but a few drop-in statements writing as result the "java object graph creation code with content" output to System.out
would also work.
So, how can I realize this in the most efficient way?