由于某种原因,在单元测试中执行的方法内的循环不止一次被执行。因此,我得到ConcurrentModificationException
。为了简化,方法循环遍历对象,使用Runnable
参数对每个对象执行其他方法。这在部署应用程序时工作正常,但在单元测试期间,循环执行多次,我收到错误。
代码示例:
@RunWith(JukitoRunner.class)
public class MyTest {
@Inject
MainService mainService;
@Test
public void testMain(){
mainService.setData(mainService.getSelectedData());
}
}
public class MainService {
List<Data> data = new ArrayList<Data>();
List<Field> fields = new ArrayList<Field>();
public MainService(){
/* this.fields is filled here*/
data.add(/*data obj*/);
data.add(/*data obj*/);
data.add(/*data obj*/);
}
public List<Data> getSelectedData(){
/* alghoritm to filter data */
return data; /*returns List with 1 and 2nd data objects from this.data*/
}
private void deleteEl(Field field, Runnable callback){
fields.remove(field);
for (ListIterator<Data> i = data.listIterator(); i.hasNext();) {
Data data = i.next();
if(data.something()) i.remove();
}
if (callback != null) {
callback.run();
}
}
public void setData(List<Data> selected){
for(Field field : fields){// checked with debug, this gets executed more than once, why?! It should run only once. ConcurrentModificationException gets thrown here.
if(field instanceof Object){
deleteEl(field, new Runnable(){
@Override
public void run(){
create(selected); //won't post create() code, since even commenting this, does not help. Error persists
}
})
}
}
}
}
答案 0 :(得分:2)
发生异常是因为您在迭代字段列表fields
时从deleteEl
列表中删除了一个字段(for(Field field : fields)
方法中的第一行)。
顺便说一下。我假设(field instanceof Object)
的检查总是返回true。