何らかの理由で、ユニットテストで実行されるメソッド内部のループが何度か実行されます。そしてそのために私はConcurrentModificationException
を得る。これを短くするには、メソッドはオブジェクトをループし、各オブジェクトの他のメソッドをRunnable
パラメータで実行します。これは、アプリケーションがデプロイされたときにうまく動作しますが、ユニットテスト中にループが複数回実行され、エラーが発生します。ユニットテストループが複数回実行される
コード例:フィールドのリストを反復処理しているときに(fields
リスト(deleteEl
メソッドの最初の行)からfor(Field field : fields)
をフィールドを削除するため
をところで
@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
}
})
}
}
}
}
いいえ、重複していません – CrazySabbath
あなたはステップバイステップでデバッグしたり、ブレークポイントを設定して原因は?どのようなエラーがスローされますか?なぜアサーションのないテストケースがあるのですか? – PanBrambor
'fields'を反復しながら削除します。これはテストに関係しないバグです。 –