Convert ContactPreferenceTest to a robolectric test.

Robolectric tests are much faster than instrumentation tests.

Test: make RunEmergencyInfoRoboTests
Change-Id: If02515a0bbc40c46a05955a299d95b221b9049c2
diff --git a/src/com/android/emergency/preferences/ContactPreference.java b/src/com/android/emergency/preferences/ContactPreference.java
index 8cdb057..ebe1dea 100644
--- a/src/com/android/emergency/preferences/ContactPreference.java
+++ b/src/com/android/emergency/preferences/ContactPreference.java
@@ -54,6 +54,7 @@
 
     private static final String TAG = "ContactPreference";
 
+    private final ContactFactory mContactFactory;
     private EmergencyContactManager.Contact mContact;
     @Nullable private RemoveContactPreferenceListener mRemoveContactPreferenceListener;
     @Nullable private AlertDialog mRemoveContactDialog;
@@ -69,11 +70,37 @@
     }
 
     /**
+     * Interface for getting a contact for a phone number Uri.
+     */
+    public interface ContactFactory {
+        /**
+         * Gets a {@link EmergencyContactManager.Contact} for a phone {@link Uri}.
+         *
+         * @param context The context to use.
+         * @param phoneUri The phone uri.
+         * @return a contact for the given phone uri.
+         */
+        EmergencyContactManager.Contact getContact(Context context, Uri phoneUri);
+    }
+
+    /**
      * Instantiates a ContactPreference that displays an emergency contact, taking in a Context and
      * the Uri.
      */
     public ContactPreference(Context context, @NonNull Uri phoneUri) {
+        this(context, phoneUri, new ContactFactory() {
+            @Override
+            public EmergencyContactManager.Contact getContact(Context context, Uri phoneUri) {
+                return EmergencyContactManager.getContact(context, phoneUri);
+            }
+        });
+    }
+
+    @VisibleForTesting
+    public ContactPreference(Context context, @NonNull Uri phoneUri,
+            @NonNull ContactFactory contactFactory) {
         super(context);
+        mContactFactory = contactFactory;
         setOrder(DEFAULT_ORDER);
 
         setPhoneUri(phoneUri);
@@ -87,7 +114,7 @@
                 mRemoveContactDialog != null) {
             mRemoveContactDialog.dismiss();
         }
-        mContact = EmergencyContactManager.getContact(getContext(), phoneUri);
+        mContact = mContactFactory.getContact(getContext(), phoneUri);
 
         setTitle(mContact.getName());
         setKey(mContact.getPhoneUri().toString());
diff --git a/tests/instrumentation/src/com/android/emergency/preferences/ContactPreferenceTest.java b/tests/instrumentation/src/com/android/emergency/preferences/ContactPreferenceTest.java
deleted file mode 100644
index d2ec9fd..0000000
--- a/tests/instrumentation/src/com/android/emergency/preferences/ContactPreferenceTest.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.emergency.preferences;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.app.Instrumentation;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.net.Uri;
-import android.provider.ContactsContract;
-import android.test.ActivityInstrumentationTestCase2;
-import android.test.suitebuilder.annotation.MediumTest;
-
-import com.android.emergency.ContactTestUtils;
-import com.android.emergency.edit.EditInfoActivity;
-
-/**
- * Tests for {@link ContactPreference}.
- */
-@MediumTest
-public class ContactPreferenceTest extends ActivityInstrumentationTestCase2<EditInfoActivity> {
-    private static final String NAME = "Jake";
-    private static final String PHONE_NUMBER = "123456";
-    private ContactPreference mContactPreference;
-    private Uri mPhoneUri;
-
-    public ContactPreferenceTest() {
-        super(EditInfoActivity.class);
-    }
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mPhoneUri =
-                ContactTestUtils.createContact(getActivity().getContentResolver(),
-                        NAME,
-                        PHONE_NUMBER);
-        mContactPreference = new ContactPreference(getActivity(), mPhoneUri);
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        assertThat(ContactTestUtils.deleteContact(getActivity().getContentResolver(),
-                NAME,
-                PHONE_NUMBER)).isTrue();
-        super.tearDown();
-    }
-
-    public void testContactPreference() {
-        assertThat(mContactPreference.getPhoneUri()).isEqualTo(mPhoneUri);
-        assertThat(mContactPreference.getContact().getName()).isEqualTo(NAME);
-        assertThat(mContactPreference.getContact().getPhoneNumber()).isEqualTo(PHONE_NUMBER);
-
-        assertThat(mContactPreference.getRemoveContactDialog()).isNull();
-        mContactPreference.setRemoveContactPreferenceListener(
-                new ContactPreference.RemoveContactPreferenceListener() {
-                    @Override
-                    public void onRemoveContactPreference(ContactPreference preference) {
-                        // Do nothing
-                    }
-                });
-        assertThat(mContactPreference.getRemoveContactDialog()).isNotNull();
-    }
-
-    public void testDisplayContact() throws Throwable {
-        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_VIEW);
-        intentFilter.addDataType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
-        Instrumentation.ActivityMonitor activityMonitor =
-                getInstrumentation().addMonitor(intentFilter, null, true /* block */);
-        mContactPreference.displayContact();
-
-        assertThat(getInstrumentation().checkMonitorHit(activityMonitor, 1 /* minHits */)).isTrue();
-    }
-
-    public void testCallContact() throws Throwable {
-        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CALL);
-        intentFilter.addDataScheme("tel");
-        Instrumentation.ActivityMonitor activityMonitor =
-                getInstrumentation().addMonitor(intentFilter, null, true /* block */);
-        mContactPreference.callContact();
-
-        assertThat(getInstrumentation().checkMonitorHit(activityMonitor, 1 /* minHits */)).isTrue();
-    }
-}
diff --git a/tests/robolectric/Android.mk b/tests/robolectric/Android.mk
new file mode 100644
index 0000000..88a864c
--- /dev/null
+++ b/tests/robolectric/Android.mk
@@ -0,0 +1,53 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_JAVA_LIBRARIES := \
+    junit \
+    platform-robolectric-prebuilt \
+    sdk_vcurrent
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    platform-system-robolectric \
+    truth-prebuilt \
+    emergencyinfo-test-common
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_INSTRUMENTATION_FOR := EmergencyInfo
+LOCAL_MODULE := EmergencyInfoRoboTests
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+#############################################################
+# EmergencyInfo runner target to run the previous target. #
+#############################################################
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := RunEmergencyInfoRoboTests
+
+LOCAL_SDK_VERSION := current
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    EmergencyInfoRoboTests
+
+LOCAL_TEST_PACKAGE := EmergencyInfo
+
+LOCAL_INSTRUMENT_SOURCE_DIRS := $(dir $(LOCAL_PATH))../src
+
+include prebuilts/misc/common/robolectric/run_robotests.mk
diff --git a/tests/robolectric/src/com/android/emergency/TestConfig.java b/tests/robolectric/src/com/android/emergency/TestConfig.java
new file mode 100644
index 0000000..8de556f
--- /dev/null
+++ b/tests/robolectric/src/com/android/emergency/TestConfig.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package com.android.emergency;
+
+/**
+ * Constants for Robolectric config
+ */
+public class TestConfig {
+    public static final int SDK_VERSION = 23;
+    public static final String MANIFEST_PATH = "packages/apps/EmergencyInfo/AndroidManifest.xml";
+}
diff --git a/tests/robolectric/src/com/android/emergency/preferences/ContactPreferencesTest.java b/tests/robolectric/src/com/android/emergency/preferences/ContactPreferencesTest.java
new file mode 100644
index 0000000..81493f7
--- /dev/null
+++ b/tests/robolectric/src/com/android/emergency/preferences/ContactPreferencesTest.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.emergency.preferences;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import android.app.Instrumentation;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.ContextWrapper;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.ActivityInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.net.Uri;
+import android.os.Looper;
+import android.provider.ContactsContract;
+import android.test.suitebuilder.annotation.SmallTest;
+
+import com.android.emergency.ContactTestUtils;
+import com.android.emergency.EmergencyContactManager;
+import com.android.emergency.TestConfig;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.Shadows;
+import org.robolectric.annotation.Config;
+
+/** Unit tests for {@link ContactPreferences}. */
+@SmallTest
+@RunWith(RobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class ContactPreferencesTest {
+    private static final String NAME = "Jake";
+    private static final String PHONE_NUMBER = "123456";
+    @Mock private PackageManager mPackageManager;
+    @Mock private ContactPreference.ContactFactory mContactFactory;
+    @Mock private EmergencyContactManager.Contact mContact;
+    private ContextWrapper mContext;
+    private ContactPreference mPreference;
+    private Uri mPhoneUri;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+
+        mContext = spy(RuntimeEnvironment.application);
+        doReturn(mPackageManager).when(mContext).getPackageManager();
+
+        mPhoneUri = ContactTestUtils.createContact(
+                mContext.getContentResolver(), NAME, PHONE_NUMBER);
+
+        when(mContactFactory.getContact(any(), any())).thenReturn(mContact);
+        when(mContact.getName()).thenReturn(NAME);
+        when(mContact.getPhoneUri()).thenReturn(mPhoneUri);
+        when(mContact.getPhoneNumber()).thenReturn(PHONE_NUMBER);
+        when(mContact.getContactLookupUri()).thenReturn(mPhoneUri);
+
+        mPreference = new ContactPreference(mContext, mPhoneUri, mContactFactory);
+    }
+
+    @Test
+    public void testContactPreference() {
+        assertThat(mPreference.getPhoneUri()).isEqualTo(mPhoneUri);
+        assertThat(mPreference.getContact().getName()).isEqualTo(NAME);
+        assertThat(mPreference.getContact().getPhoneNumber()).isEqualTo(PHONE_NUMBER);
+
+        assertThat(mPreference.getRemoveContactDialog()).isNull();
+        mPreference.setRemoveContactPreferenceListener(
+                new ContactPreference.RemoveContactPreferenceListener() {
+                    @Override
+                    public void onRemoveContactPreference(ContactPreference preference) {
+                        // Do nothing
+                    }
+                });
+        assertThat(mPreference.getRemoveContactDialog()).isNotNull();
+    }
+
+    @Test
+    public void testDisplayContact() throws Throwable {
+        mPreference.displayContact();
+
+        Intent intent = new Intent(Intent.ACTION_VIEW);
+        intent.setData(mPhoneUri);
+        assertThat(Shadows.shadowOf(mContext).getNextStartedActivity().filterEquals(intent))
+                .isTrue();
+    }
+
+    @Test
+    public void testCallContact() throws Throwable {
+        final String name = "a name";
+        final String packageName = "a package name";
+
+        List<ResolveInfo> resolveInfos = new ArrayList<>();
+        ResolveInfo resolveInfo = new ResolveInfo();
+        resolveInfo.activityInfo = new ActivityInfo();
+        resolveInfo.activityInfo.name = name;
+        resolveInfo.activityInfo.packageName = packageName;
+        resolveInfos.add(resolveInfo);
+        when(mPackageManager.queryIntentActivities(any(Intent.class), anyInt()))
+                .thenReturn(resolveInfos);
+
+        mPreference.callContact();
+
+        Intent intent = new Intent(Intent.ACTION_CALL);
+        intent.setData(Uri.parse("tel:" + PHONE_NUMBER));
+        intent.setComponent(new ComponentName(packageName, name));
+        assertThat(Shadows.shadowOf(mContext).getNextStartedActivity().filterEquals(intent))
+                .isTrue();
+    }
+}