2017-08-09 120 views
0

由於某種原因,在單元測試中執行的方法中的循環會多次執行。正因爲如此,我得到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

不,它不是重複的 – CrazySabbath

+0

你試過一步一步地調試它並且/或者設置斷點來檢查可能是什麼原因在哪裏?拋出什麼錯誤?爲什麼有沒有斷言的測試用例? – PanBrambor

+1

您在遍歷'fields'時刪除。這是一個與測試無關的錯誤。 –

回答

2

發生異常,因爲你從fields列表(deleteEl方法第一行)刪除字段,同時遍歷字段列表(for(Field field : fields)

順便說一句我承擔對(field instanceof Object)的檢查總是返回true

+0

如果'field'爲空,則'field instanceof Object'將返回false。所以這是一個複雜的空檢查,我猜... – nbrooks

+0

明確檢查'field!= null'會更容易理解 –

+0

'順便說一句。我假設(字段instanceof Object)的檢查總是返回true。錯誤的假設。無論如何,問題與@nbrooks筆記有關,儘管它有點複雜 – CrazySabbath