Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7165163
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T14:11:43+00:00 2026-05-28T14:11:43+00:00

I want to test the functionality of an activity that contains a ListFragment ,

  • 0

I want to test the functionality of an activity that contains a ListFragment, but I am not sure how to go about this. I have tried a lot, but nothing seems to work.

So the activity I want to test contains a ListFragment, and this ListFragment is populated by using LoaderManager.LoaderCallbacks and a CursorLoader. This CursorLoader queries a ContentProvider, and the onLoadFinished() method swaps the Cursor into the ListAdapter of the ListView.

What I want to achieve with my test is to start the activity and then test if the ListView is populated with the correct data. Because the content of my ContentProvider is based on content retrieved from a webservice with a Service, I thought I should mock the ContentProvider to ensure the test data is what the test expects. But this is easier said than done. I have run into all sorts of problems.

I believe most problems come from the fact that my data is loaded through an AsyncTask by the CursorLoader. I start my loader in the onCreate() method of my ListFragment, but after onCreate() finishes my test executes, because it does not wait for the AsyncTask loading to be finished. And because the loading does not finish before the test executes, my test fails.

This is my test class:

public class TopscorersActivityTest extends ActivityUnitTestCase<TopscorersActivity> {

    public static final int TEST_POSITION = 1;
    public static final String TEST_NAME = "name";
    public static final String TEST_CLUB = "club";
    public static final int TEST_GOALS = 2;

    private Intent mStartIntent;
    private ListView mListView;
    private Context mContext;
    private ContentResolver mContentResolver;

    public TopscorersActivityTest() {
        super(TopscorersActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        mStartIntent = new Intent();

        mContext = new RenamingDelegatingContext(getInstrumentation().getTargetContext(), "test");
        mContentResolver = mContext.getContentResolver();
        setActivityContext(mContext);

        // Setup database fixture
        ContentValues values = new ContentValues();
        values.put(Topscorers.TOPSCORER_POSITION, TEST_POSITION);
        values.put(Topscorers.TOPSCORER_NAME, TEST_NAME);
        values.put(Topscorers.TOPSCORER_CLUB, TEST_CLUB);
        values.put(Topscorers.TOPSCORER_GOALS, TEST_GOALS);

        mContentResolver.delete(Topscorers.CONTENT_URI, null, null);
        mContentResolver.insert(Topscorers.CONTENT_URI, values);
    }

    public void testPreConditions() {
        startActivity(mStartIntent, null, null);
        assertNotNull(getActivity());

        mListView = (ListView) getActivity().findViewById(android.R.id.list);
        assertNotNull(mListView);

        Cursor cursor = mContentResolver.query(Topscorers.CONTENT_URI, null, null, null, null);
        assertEquals(1, cursor.getCount());
    }

    public void testListPopulatedCorrectly() {
        startActivity(mStartIntent, null, null);
        getInstrumentation().waitForIdleSync();

        ListView listView = (ListView) getActivity().findViewById(android.R.id.list);
        assertEquals(1, listView.getCount());
    }
}

The testPreConditions() test succeeds, but the testListPopulatedCorrectly() fails because listView.getCount() returns 0.

How can I achieve what I want? Am I even going in the right direction with my test code? Or should I take another approach? If so, what?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T14:11:43+00:00Added an answer on May 28, 2026 at 2:11 pm

    Since I have not received any response on my question, I will answer my own question. I decided to go with another approach than used in the code sample of my question. The basic outline of my new approach is:

    • I switched my base test class to ActivityInstrumentationTestCase2

    • I created a MockHttpClient class, which I inject into my code, and this MockHttpClient returns a successful HttpResponse with a response entity containing my JSON fixture data. The MockHttpClient class implements the HttpClient interface and returns null for all methods but the execute() methods that should return a HttpResponse object.

    • Because the ListFragment I am testing registers a BroadcastReceiver to determine that the data retrieval service is finished, I also register a BroadcastReceiver in my test. I block my test with a CountDownLatch until the broadcast is received.

    • When the broadcast is received, I use Thread.sleep(500) to let my activity update the ListView. After that I run my assertions against the ListView.

    • I annotated my test with FlakyTest(tolerance=5), which executes the test up to 5 times when assertions fail.

    I am not sure if this is a good approach, so please feel free to leave some comments. But for now it works. To conclude my answer, the new code for my test:

    TEST CLASS

    public class TopscorersActivityTest extends ActivityInstrumentationTestCase2<TopscorersActivity> {
    
        public static final String JSON = "[" 
            +   "{\"position\": 1, \"name\": \"Bas Dost\", \"club\": \"sc Heerenveen\", \"goals\": \"16\" },"
            +   "{\"position\": 2, \"name\": \"Dries Mertens\", \"club\": \"PSV\", \"goals\": \"13\"},"
            +   "{\"position\": 3, \"name\": \"Luuk de Jong\", \"club\": \"FC Twente\", \"goals\": \"12\"}"
            + "]";
    
        private TopscorersActivity mActivity;
        private ListView mListView;
    
        public TopscorersActivityTest() {
            super("com.example.package", TopscorersActivity.class);
        }
    
        @Override
        protected void setUp() throws Exception {
            super.setUp();
            ConnectivityUtils.setHttpClient(MockHttpClient.createInstance(JSON));
            mActivity = getActivity();
            mListView = (ListView) getActivity().findViewById(android.R.id.list);
        }
    
        @Override
        protected void tearDown() throws Exception {
            super.tearDown();
            ConnectivityUtils.setHttpClient(null);
        }
    
        @MediumTest
        public void testPreconditions() {
            assertNotNull(mActivity);
            assertNotNull(mListView);
            assertEquals(0, mListView.getFirstVisiblePosition());
        }
    
        @FlakyTest(tolerance=5)
        @LargeTest
        public void testListItemsPopulatedCorrectly() throws InterruptedException {
            waitForBroadcast(mActivity, TopscorersService.BROADCAST_ACTION, Intent.CATEGORY_DEFAULT);
    
            assertEquals(3, mListView.getCount());
    
            // First list item
            View view = mListView.getChildAt(0);
            assertNotNull(view);
    
            TextView positionTextView = (TextView) view.findViewById(R.id.topscorerPositionTextView);
            TextView nameTextView = (TextView) view.findViewById(R.id.topscorerNameTextView);
            TextView goalsTextView = (TextView) view.findViewById(R.id.topscorerGoalsTextView);
    
            assertEquals("1", positionTextView.getText());
            assertEquals("16", goalsTextView.getText());
            assertEquals(
                Html.fromHtml("Bas Dost<br /><i>sc Heerenveen</i>").toString(), 
                nameTextView.getText().toString()
            );
    
            // Second list item
            view = mListView.getChildAt(1);
            assertNotNull(view);
    
            positionTextView = (TextView) view.findViewById(R.id.topscorerPositionTextView);
            nameTextView = (TextView) view.findViewById(R.id.topscorerNameTextView);
            goalsTextView = (TextView) view.findViewById(R.id.topscorerGoalsTextView);
    
            assertEquals("2", positionTextView.getText());
            assertEquals("13", goalsTextView.getText());
            assertEquals(
                    Html.fromHtml("Dries Mertens<br /><i>PSV</i>").toString(), 
                    nameTextView.getText().toString()
            );
    
            // Third list item
            view = mListView.getChildAt(2);
            assertNotNull(view);
    
            positionTextView = (TextView) view.findViewById(R.id.topscorerPositionTextView);
            nameTextView = (TextView) view.findViewById(R.id.topscorerNameTextView);
            goalsTextView = (TextView) view.findViewById(R.id.topscorerGoalsTextView);
    
            assertEquals("3", positionTextView.getText());
            assertEquals("12", goalsTextView.getText());
            assertEquals(
                    Html.fromHtml("Luuk de Jong<br /><i>FC Twente</i>").toString(), 
                    nameTextView.getText().toString()
            );
        }
    
        private void waitForBroadcast(Context context, String action, String category) throws InterruptedException {
            final CountDownLatch signal = new CountDownLatch(1);
    
            IntentFilter intentFilter = new IntentFilter(action);
            intentFilter.addCategory(category);
            BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    signal.countDown();
                }
            };
    
            context.registerReceiver(broadcastReceiver, intentFilter);
            signal.await(1500, TimeUnit.MILLISECONDS);
            context.unregisterReceiver(broadcastReceiver);
            Thread.sleep(500);
        }
    }
    

    MOCK HTTP CLIENT CLASS

    public class MockHttpClient implements HttpClient {
        private HttpResponse mHttpResponse;
    
        /**
         * A MockHttpClient with an HTTP 1.1 200 OK response
         * 
         * @param response
         * @return
         * @throws UnsupportedEncodingException
         */
        public static HttpClient createInstance(String response) 
                throws UnsupportedEncodingException {
    
            return createInstance(200, "OK", response);
        }
    
        /**
         * A MockHttpClient with an HTTP 1.1 response
         * 
         * @param statusCode
         * @param reasonPhrase
         * @param response
         * @return
         * @throws UnsupportedEncodingException
         */
        public static HttpClient createInstance(int statusCode, String reasonPhrase, String response) 
            throws UnsupportedEncodingException {
    
            return createInstance(HttpVersion.HTTP_1_1, statusCode, reasonPhrase, response);
        }
    
        /**
         * 
         * @param version
         * @param statusCode
         * @param reasonPhrase
         * @param response
         * @return
         * @throws UnsupportedEncodingException
         */
        public static HttpClient createInstance(ProtocolVersion version, int statusCode, String reasonPhrase, String response)
                throws UnsupportedEncodingException {
    
            StatusLine statusLine = new BasicStatusLine(version, statusCode, reasonPhrase);
            HttpResponse httpResponse = new BasicHttpResponse(statusLine);
            HttpEntity httpEntity = new StringEntity(response);
            httpResponse.setEntity(httpEntity);
            return new MockHttpClient(httpResponse);
        }
    
        /**
         * Constructor.
         * 
         * @param httpResponse
         */
        private MockHttpClient(HttpResponse httpResponse) {
            mHttpResponse = httpResponse;
        }
    
        /**
         * 
         * @param request
         * @return
         */
        public HttpResponse execute(HttpUriRequest request) {
            return mHttpResponse;
        }
    
        @Override
        public HttpResponse execute(HttpUriRequest request, HttpContext context)
                throws IOException, ClientProtocolException {
            return mHttpResponse;
        }
    
        @Override
        public HttpResponse execute(HttpHost target, HttpRequest request)
                throws IOException, ClientProtocolException {
            return mHttpResponse;
        }
    
        @Override
        public <T> T execute(HttpUriRequest arg0,
                ResponseHandler<? extends T> arg1) throws IOException,
                ClientProtocolException {
            return null;
        }
    
        @Override
        public HttpResponse execute(HttpHost target, HttpRequest request,
                HttpContext context) throws IOException,
                ClientProtocolException {
            return mHttpResponse;
        }
    
        @Override
        public <T> T execute(HttpUriRequest arg0,
                ResponseHandler<? extends T> arg1, HttpContext arg2)
                throws IOException, ClientProtocolException {
            return null;
        }
    
        @Override
        public <T> T execute(HttpHost arg0, HttpRequest arg1,
                ResponseHandler<? extends T> arg2) throws IOException,
                ClientProtocolException {
            return null;
        }
    
        @Override
        public <T> T execute(HttpHost arg0, HttpRequest arg1,
                ResponseHandler<? extends T> arg2, HttpContext arg3)
                throws IOException, ClientProtocolException {
            return null;
        }
    
        @Override
        public ClientConnectionManager getConnectionManager() {
            return null;
        }
    
        @Override
        public HttpParams getParams() {
            return null;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i want the following functionality. input : this is test <b> bold text </b>
I want to test if a sentence contains anything else than white-space characters. This
I have built an API that I want to test. By that reason I'm
I have written servlet.I want to test the functionality of my servlet class ,so
I have searched, and this post is closest, but not exactly the same. I
I have some code that uses the Swing/AWT printing functionality that I want to
We want to test email functionality on our staging server, but we don't want
I want to test Add new item activity in my application. When user fills
I have a requirment in my task that there is a activity that recieves
I have a GWT application and wanna to test load and functionality using a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.