drlobo
drlobo

Reputation: 2159

Android Unit test for a PreferenceFragment

I have a few PreferenceFragment classes that I need to test:

public class MyPref extends PreferenceFragment

how do I test them ?

for example I have tried to:

public class MyPrefTester extends ActivityInstrumentationTestCase2<MyPref> 

However this fails because this Android test class requires that the parameter inherit from Activity. And PreferenceFragment inherits from Fragment (which is used by an Activity).

What can some suggest ?

Upvotes: 0

Views: 647

Answers (1)

Ahmed Zayed
Ahmed Zayed

Reputation: 2185

I have been working on the same problem on the last couple of weeks, here's my approach:

  1. Create an ActivityInstrumentationTestCase2 for the activity from which this fragment will be instantiated.
  2. Go to the preferences fragment screen using robotium library.
  3. Make changes using robotium.
  4. Modify onDestroy method of the fragment to broadcast an intent with the changes made to preferences.
  5. Create a broadcast receiver in your ActivityInstrumentationTestCase2 that you are using for this test case.
  6. Go back from this fragment to make sure that the preferences are saved and onDestroy is called
  7. On receiving the intent when onDestroy, save the changes.
  8. Go back to the fragment and make sure that the received saved values are the same as the shown. Hoping that this helps.

Upvotes: 1

Related Questions