Reputation: 1564
I have method which takes a domain object (a very complex nested object tree) as parameter does some operation and returns a result. I need to create junit test for this method for which i need to set data into the complex object. I want to automate the process of creating mock data for my junit test.I want:Those objects/primitives of the complex object tree which are being called in my method should be identified automatically (by analysing the code or otherwise) and setters for those fields should be called. Any help is appreciated.
Upvotes: 1
Views: 1128
Reputation: 1076
I haven't tried PODAM (POjo Data Mocker), but it is a tool to "autofill pojos with made-up data".
Pojo pojo = new PodamFactoryImpl().manufacturePojo(Pojo.class);
You could check it out - it seems to be configurable, and as default to use both constructor arguments and setters.
If you feel like experimenting with your own / creating your own test-utility, you could do something along these lines (- I admit that the string check on "set" is somewhat ugly: it could be a method that is NOT a setter. The logic could be expanded: Is the next character in Uppercase? Does it match a field name?)
public void populateObjectWithRandomValuesUsingReflection(Object object) {
List<Object> argsList;
for (Method method : object.getClass().getMethods()){
argsList = new ArrayList();
if (resemblesASetterMethod(method)){
for (Class<?> parameterClass : method.getParameterTypes()){
if (parameterClass.isPrimitive()){
argsList.add(getRandomValueOfPrimitive(parameterClass));
} else {
throw new UnsupportedOperationException("This jUnit test utility does not yet support non-primitive types.");
}
}
invokeMethod(method, object, argsList.toArray());
}
}
}
private void invokeMethod(Method method, Object object, Object[] args) {
try {
method.invoke(object, args);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
private boolean resemblesASetterMethod(Method method){
return method.getName().startsWith("set");
}
Above example only support primitives, but again, you could extend this example code.
For creating (pseudo) random values there are frameworks, fx:
Upvotes: 1