0
我想修改一個類的私人領域,說A類,這是另一個類的內部類說B類我試着java反映包,並可以得到該私人領域,但是當我把它分配給模擬對象就抱怨它不能在字段設置爲正確的類不能設置內部類的私人領域使用java反射
這裏是我的代碼:
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..
我看不出我的步驟有什麼問題,任何人都可以幫忙嗎?謝謝。
這個想法是你通過它的構造函數或屬性注入實現到類中。然後在測試時注入一個模擬代替。那麼爲什麼你會這樣黑客攻擊呢? –
「field.set」的第一個參數必須是要設置其字段的對象,而不是某個類。 –
我需要這樣做的原因是因爲該查找服務佔用了太多的內存並拋出了堆消息,所以我想在測試中嘲笑它。 – user468587