Here you can find the source of setFields(final Map
Parameter | Description |
---|---|
fields | Fields to be injected into the target object |
target | Object which will have mocks injected into it |
public static void setFields(final Map<String, Object> fields, final Object target)
//package com.java2s; //License from project: Open Source License import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Map; public class Main { /**// ww w. j av a2s . c om * Allows for easy injection of mocks into private or protected fields. * <br/> * Example: * <pre> * TestContainer container = new TestContainer(); * Map<String, Object> fields = new HashMap<String, Object>(); * TestObject mockTestObject = mock(TestObject.class); * fields.put("privateMemberName", mockTestObject); * MockUtils.setFields(fields, container); * </pre> * * <b>This method can be used on private fields, static fields, or * final fields</b> * * @param fields Fields to be injected into the target object * @param target Object which will have mocks injected into it */ public static void setFields(final Map<String, Object> fields, final Object target) { for (Field field : target.getClass().getDeclaredFields()) { if (fields.containsKey(field.getName())) { try { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); if (Modifier.isFinal(field.getModifiers())) { modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); } if (Modifier.isStatic(field.getModifiers())) { field.set(null, fields.get(field.getName())); } else { field.set(target, fields.get(field.getName())); } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } } } }