Shubham Chaudhary
Shubham Chaudhary

Reputation: 51143

Mocking findViewById response with Robolectric and Mockito

I have a custom ListView say CustomListView:

In a fragment there is:

<com.custom.CustomListView
    android:id="@+id/custom_listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

and in that fragment's source, I have

private CustomListView mCustomListView;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mContext = getActivity();

    mCustomListView = mContext.findViewById(R.id.custom_listview);
}

Then there is some method later:

public void doSomethingOnReceivingData(Data data) {
    mCustomListView.someCustomMethod(data);
}

I want to write test for doSomethingOnReceivingData(Data) method.

I can not figure out how to mock the listview so that I can continue with the test (ArgumentCaptors and stuff)?

Upvotes: 2

Views: 1962

Answers (2)

Steve C
Steve C

Reputation: 1104

@RunWith(MockitoJUnitRunner.class)
public class MainActivityFragmentTest {

    @Mock
    private CustomListView mCustomListView;

    @InjectMocks
    private MainActivityFragment fragment;

    @Test
    public void doSomethingOnReceivingData_callsCustomListView() {
        final String data = "data";

        fragment.doSomethingOnReceivingData(data);

        verify(mCustomListView).someCustomMethod(eq(data));
    }

}

Upvotes: 1

Eugen Martynov
Eugen Martynov

Reputation: 20140

I would give to list field package local access and mock it in test directly. For our app it is already package accessible since we use Butterknife

Upvotes: 1

Related Questions