Last active
September 16, 2016 13:25
-
-
Save richashworth/1537018 to your computer and use it in GitHub Desktop.
Mock Object Populator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi!
You'll have a NPE at line 26 if the populateMockObject is called.