ReflectionUtils { public void setFieldIntoObject(Object object, String fieldName, Object value) { Field declaredField = getDeclaredField(object, fieldName); if (declaredField == null) { throw new CloudRuntimeException(String.format("Field [fieldName=%s] does not exists into object [%s].", fieldName, object)); } declaredField.setAccessible(true); try { declaredField.set(object, value); } catch (IllegalArgumentException | IllegalAccessException e) { throw new CloudRuntimeException(String.format("Fail to set field [fieldName=%s] into object [%s] with the value [%s].", fieldName, object, value), e); } }  void setFieldIntoObject(Object object, String fieldName, Object value);  }
@Test public void setFieldIntoObjectTest() throws Exception { HostResources host = new HostResources(); String expectedName = "name"; spy.setFieldIntoObject(host, "hostName", expectedName); Mockito.verify(spy).getDeclaredField(Mockito.any(), Mockito.anyString()); Assert.assertEquals(expectedName, host.getHostName()); }