1 package org.robolectric.shadows; 2 3 import static com.google.common.truth.Truth.assertThat; 4 5 import android.app.Activity; 6 import android.app.FragmentManager; 7 import android.os.Bundle; 8 import android.preference.Preference; 9 import android.preference.PreferenceFragment; 10 import androidx.test.ext.junit.runners.AndroidJUnit4; 11 import org.junit.Before; 12 import org.junit.Test; 13 import org.junit.runner.RunWith; 14 import org.robolectric.R; 15 import org.robolectric.Robolectric; 16 17 /** 18 * Current Android examples show adding a PreferenceFragment as part of the hosting Activity 19 * lifecycle. This resulted in a null pointer exception when trying to access a Context while 20 * inflating the Preference objects defined in xml. This class tests that path. 21 */ 22 @RunWith(AndroidJUnit4.class) 23 public class ShadowPreferenceActivityTestWithFragment { 24 private TestPreferenceActivity activity = Robolectric.setupActivity(TestPreferenceActivity.class); 25 private TestPreferenceFragment fragment; 26 private static final String FRAGMENT_TAG = "fragmentPreferenceTag"; 27 28 @Before before()29 public void before() { 30 this.fragment = (TestPreferenceFragment) this.activity.getFragmentManager().findFragmentByTag(FRAGMENT_TAG); 31 } 32 33 @Test fragmentIsNotNull()34 public void fragmentIsNotNull() { 35 assertThat(this.fragment).isNotNull(); 36 } 37 38 @Test preferenceAddedWithCorrectDetails()39 public void preferenceAddedWithCorrectDetails() { 40 Preference preference = fragment.findPreference("edit_text"); 41 assertThat(preference).isNotNull(); 42 assertThat(preference.getTitle()).isEqualTo("EditText Test"); 43 assertThat(preference.getSummary()).isEqualTo(""); 44 } 45 46 private static class TestPreferenceActivity extends Activity { 47 @Override onCreate(Bundle savedInstanceState)48 protected void onCreate(Bundle savedInstanceState) { 49 super.onCreate(savedInstanceState); 50 51 FragmentManager fragmentManager = this.getFragmentManager(); 52 TestPreferenceFragment fragment = new TestPreferenceFragment(); 53 fragmentManager.beginTransaction().replace(android.R.id.content, fragment, FRAGMENT_TAG).commit(); 54 } 55 } 56 57 public static class TestPreferenceFragment extends PreferenceFragment { 58 @Override onCreate(Bundle savedInstanceState)59 public void onCreate(Bundle savedInstanceState) { 60 super.onCreate(savedInstanceState); 61 this.addPreferencesFromResource(R.xml.preferences); 62 } 63 } 64 } 65