How to set Unit Test to Fragment in Android

后端 未结 4 1270
梦如初夏
梦如初夏 2020-12-23 14:10

I want to unit test an Android Fragment class.

Can I set up a test using AndroidTestCase or do I need to use ApplicationTestCase?

Are there any useful exampl

4条回答
  •  一生所求
    2020-12-23 14:38

    Adding to @abhijit.mitkar's answer.

    Given a scenario that your fragment is not a public member in the activity under test.

    protected void setUp() {
       mActivity = getActivity();
       mFragment = new TheTargetFragment();
    
       FragmentTransaction transaction = mActivity.getSupportFragmentManager().beginTransaction();
       transaction.add(R.id.fragment_container, mFragment, "FRAGMENT_TAG");
       transaction.commit();
    }
    

    The purpose of the code above is to replace the fragment with a new fragment object that we have access to.

    The code below will allow you to gain access to the fragments UI members.

    TextView randomTextView= (TextView) mFragment.getView().findViewById(R.id.textViewRandom);
    

    Getting the UI from the activity will not give you the expected result.

    TextView randomTextView= (TextView) mActivity.findViewById(R.id.textViewRandom);
    

    Finally if you wish to do some changes in the UI. Like a good android developer do it in the main thread.

    mActivity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // set text view's value
        }
    });
    

    Note: You might want to give it a Thread.sleep() every a test ends. To avoid lock up, the getInstrumentation().waitForIdleSync(); does not seem to work always.

    I used ActivityInstrumentationTestCase2 since i was doing functional testing.

提交回复
热议问题