For some reason the loop inside a method, that gets executed in a unit test, gets executed more than once. And because of that I get ConcurrentModificationException
. To make it short, method loops through objects, executes other method on each object, with Runnable
parameter. This works just fine when application is deployed, but during unit testing, loop gets executed more than once and I get an error.
Code example:
@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
}
})
}
}
}
}