2017-04-18 62 views
1

我有單擊片段被替換的按鈕單擊偵聽器,並在下一個片段上傳遞參數。 代碼: -在roboelectric的單元測試期間獲得空指針異常

Fragment fragment = new CustomList(); 
      Bundle args = new Bundle(); 
      args.putString("fragment", "Custom"); 
      args.putSerializable("productBean", productBean); 
      fragment.setArguments(args); 
      fragmentManager = getActivity().getSupportFragmentManager(); 
      fragmentTransaction = fragmentManager 
        .beginTransaction(); 
      fragmentTransaction.setCustomAnimations(R.anim.slide_in, R.anim.slide_out, R.anim.slide_enter, R.anim.slide_exit); 
      fragmentTransaction.replace(R.id.container_body, fragment); 
      fragmentTransaction.addToBackStack(null); 
      fragmentTransaction.commit(); 

寫測試用例按鈕點擊: -

Button custom_btn = (Button) fragment.getView().findViewById(R.id.custom_btn); 
      custom_btn.performClick(); 

但在測試用例的執行,它顯示空指針異常,當上CustomList getArguments()片段。

productsBean = (ProductsBean) getArguments().getSerializable("productsBean"); 
+0

它的產品在代碼中,錯誤地在這裏粘貼了錯誤的代碼。好。更多的建議 –

回答

1

嘗試更改此代碼:

productsBean = (ProductsBean) getArguments().getSerializable("productsBean"); 

這個

productsBean = (ProductsBean) getArguments().getSerializable("productBean"); 

正如你所看到的,你要添加到包標籤「的ProductBean」,但是當你嘗試獲得它你使用的標籤「productsBean」,在那裏你添加了「s」charachter。

我會從那個改變開始。

+0

我會說 - 很好! –

+0

其產品在代碼中,錯誤地在這裏粘貼了錯誤的代碼。任何更多的建議@niarb –

+0

嗨@ShivamKapoor,你在哪裏調用getArguments?裏面的片段循環的唯一方法?順便說一句,你應該做一些先前的空檢查驗證,以防止NPE,如下所示: Bundle arguments = getArguments(); 如果(參數!= NULL){ // 那麼你的論點 } {其他供應 //沒有參數... } – niarb