5

I am a newbie to Android and want to do unit testing on Recycler view and its adapter using Mockito.

I have mocked the activity and trying to mock its recycler view and add my unit tests to it. I digged into Google to find a solution for it. But didn't get any references. Final after gathering some of the references I have written my test class like this.

public class PhotoViewActivityTest {
@Mock
Context context;
@InjectMocks
private PhotoViewActivity photoViewActivity;
RecyclerView recyclerView;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    recyclerView = Mockito.mock(RecyclerView.class);
    MockitoAnnotations.initMocks(this);
    photoViewActivity = mock(PhotoViewActivity.class);
}

@Test
public void checkIfRecyclerViewClicked() {
    List<PhotoListItem> items = new ArrayList<>();
    Photo photo = Mockitio.mock(Photo.class);
    items.add(photo));
    PhotoViewerListAdapter adapter = Mockito.mock(PhotoViewerListAdapter);
    adapter.setData(items);
    recycleView.setAdapter(adapter);
    // simulate first item was clicked
    recyclerView.getChildAt(0).performClick();
    //Check if method was invoked with our object
    Mockito.verify(adapter).goToDetailActivity(photo);
 }
}

But it is giving null pointer exception. I referred this How do I unit test (with JUnit or mockito) recyclerview item clicks

halfer
  • 19,824
  • 17
  • 99
  • 186
Niraj Kulal
  • 89
  • 1
  • 5
  • I am also searching for a solution to test my recycler view using mockito – hasan_shaikh Mar 03 '18 at 10:37
  • its just a recycler view with an adapter – Niraj Kulal Mar 03 '18 at 10:48
  • 1
    Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Mar 03 '18 at 11:13
  • 1
    Check Espresso, it's a framework for UI testing. There is a tool Espresso Test Recorder that write tests for you, when you run the app on your device then you add assertions after you did some action and the unit test is written alone – Mickael B. Mar 03 '18 at 13:12
  • Possible duplicate of [How do I unit test (with JUnit or mockito) recyclerview item clicks](https://stackoverflow.com/questions/42188261/how-do-i-unit-test-with-junit-or-mockito-recyclerview-item-clicks) – Ali Nem May 11 '18 at 12:37

0 Answers0