Skip to content

Instantly share code, notes, and snippets.

@richashworth
Last active September 16, 2016 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richashworth/1537018 to your computer and use it in GitHub Desktop.
Save richashworth/1537018 to your computer and use it in GitHub Desktop.
Mock Object Populator
package com.richashworth.testingutils.mocking;
import java.lang.reflect.Method;
import java.util.Map;
import static org.junit.Assert.fail;
public class MockObjectPopulator {
private DefaultValues defaultValues = new DefaultValues();
public void populateMockObject(Object obj) {
populateMockObjectWithCustomValues(obj, null);
}
public void populateMockObjectWithCustomValues(Object obj, Map<String, Object> fieldMap) {
try {
for (Method f : obj.getClass().getDeclaredMethods()) {
String methodName = f.getName();
if (methodName.startsWith("set")) {
Class type = f.getParameterTypes()[0];
String fieldName = methodName.replace("set", "");
fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
Object value;
if (fieldMap.containsKey(fieldName)) {
value = fieldMap.get(fieldName);
} else {
value = getDefaultValueByType(type);
}
if (value != null) {
f.invoke(obj, value);
}
}
}
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
private Object getDefaultValueByType(Class aClass) throws NoSuchMethodException {
String typeName = aClass.getName();
Map<String, Object> defaultValuesMap = defaultValues.getDefaultValuesMap();
Object object = defaultValuesMap.get(typeName);
return object;
}
}
@broxmik
Copy link

broxmik commented Sep 16, 2016

Hi!
You'll have a NPE at line 26 if the populateMockObject is called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment