Created
November 22, 2016 17:34
-
-
Save mshanu/283352faaa6eac44f671be6a60f8c534 to your computer and use it in GitHub Desktop.
Test util to create object and set fields
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
import org.springframework.test.util.ReflectionTestUtils; | |
import java.lang.reflect.Field; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class Mother<T> { | |
private Class<T> clazz; | |
private Map<String, Object> objectMap = new HashMap(); | |
private Mother(Class<T> clazz) { | |
this.clazz = clazz; | |
} | |
public static <T> Mother<T> forClass(Class<T> clazz) { | |
return new Mother<>(clazz); | |
} | |
public static <E> E updateField(E targetObject, String fieldName, Object value) { | |
ReflectionTestUtils.setField(targetObject, fieldName, value); | |
return targetObject; | |
} | |
public Mother<T> with(String propertyName, Object value) { | |
objectMap.put(propertyName, value); | |
return this; | |
} | |
public T build() { | |
T newInstance; | |
try { | |
newInstance = clazz.newInstance(); | |
for (Map.Entry<String, Object> eachKeyValue : objectMap.entrySet()) { | |
Field declaredField = clazz.getDeclaredField(eachKeyValue.getKey()); | |
declaredField.setAccessible(true); | |
declaredField.set(newInstance, eachKeyValue.getValue()); | |
} | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
return newInstance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment