Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.