AutowireCapableBeanFactory factory =testContext.getApplicationContext().getAutowireCapableBeanFactory(); //Autowired注解注入mock对象 for (Field field :injectFields) { field.setAccessible(true); Object object = field.get(bean); if(objectinstanceof Proxy){ Class targetClass = AopUtils.getTargetClass(object); if(targetClass ==null) return; Field[] targetFields =targetClass.getDeclaredFields(); for(Field targetField : targetFields){ targetField.setAccessible(true); if(mockObjectMap.get(targetField.getName()) ==null){ continue; } targetField.set(getTargetObject(object,mockObjectMap.get(targetField.getName()).getType()),mockObjectMap.get(targetField.getName()).getObj()); } }else{ Object realObject = factory.getBean(field.getName()); if(null != realObject){ Method[] methods = realObject.getClass().getDeclaredMethods(); for (Method method : methods) { if(method.getName().equalsIgnoreCase("set" +field.getName())){ method.invoke(realObject, mockObjectMap.get(field.getName()).getObj()); } } } } } } |