At work I had to create some test data for a junit test. The function I’m testing expects a super abstract class to be passed in and I need to test the same function for bunch of child classes. I wish I could just pass in the parent class but since it’s abstract I cannot instantiate it. I wonder if there is a way using reflection so I can instantiate the class?? Since I could not find a way, I used the following:
public void testSomeFunction() throws Exception { ParentData data1 = populate(ChildDataOne.class); //..test.. ParentData data2 = populate(ChildDataTwo.class); //..test.. } private static ParentData populate(Class clazz) throws Exception { ParentData data = clazz.newInstance(); data.setProperty1("1"); data.setProperty2("2"); data.setProperty3("3"); data.setProperty4("4"); data.setProperty5("5"); return data; }
Image may be NSFW.
Clik here to view.

Clik here to view.
