我想修改一个类的私有字段,比如类a,它是另一个类(比如类B)的内部类。我尝试了javareflect包,可以获得该私有字段,但当我将其分配给mock对象时,它抱怨它无法将该字段设置为正确的类
这是我的代码:
public class Aggregator {
public static class AMapper extends Mapper<LongWritable, Text, LongWritable, Text> {
private LookupService lookupService = null; <-- field to mock
...
}
}
我的测试代码:
aggregator = new Aggregator();
for (Class<?> c: aggregator.getClass().getClasses()) {
if (c.getName().equals("Aggregator$AMapper")) {
Field field = c.getDecalredField("lookupService");
field.setAccessible(true);
field.set(c, Mocito.mock(LookupService.class)); <-- failed here
break;
}
}
我得到的错误信息是:
java.lang.IllegalArgumentException: Can not set com.maxmind.geoip.LookupService field Aggregator$EventTypeMapper.lookupService to java.lang.Class..
我看不出我的脚怎么了,有人能帮我吗?谢谢
请参阅Java API文档字段。我认为代码应该是:
field.set(null, Mocito.mock(LookupService.class));