基于hk2框架的功能测试Mock注入
public Object getInstance(Class<?> clz){
return IocBean.get(clz.getName());
}
public Object MocK(Class<?> clz,Object...objects){
Map<String, Object> shadow=new HashMap<>();
shadow.putAll(IocBean);
for (Object object : objects) {
Class<?>[] inf= object.getClass().getInterfaces();
for (Entry<String, Object> element : shadow.entrySet()) {
//待注入的类正好是此对象,直接替换,默认object中无注入,或有注入并已经注入
if (isEquals(inf,object.getClass().getInterfaces())) {
shadow.put(element.getKey(), object);
continue;
}
//iocbean中有对象含有此对象,则注入
Field[] fields = element.getValue().getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
//iocbean中对象含有此成员变量,并且成员变量和入参object同接口类型,则更改成员变量
if (f.getAnnotation(Inject.class) != null&&isEquals(inf, f.getType().getInterfaces())) {
f.setAccessible(true);
try {
f.set(element.getValue(),object);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
return shadow.get(clz.getName());
}
public boolean isEquals(Class<?>[] clz1,Class<?>[] clz2){
for (Class<?> class1 : clz1) {
for (Class<?> class2 : clz2) {
if (class1.getName().equals(class2.getName())) {
return true;
}
}
}
return false;
}
I am a slow walker, but I never walk backwards.