1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License 15 */ 16 package com.android.settings; 17 18 import static org.junit.Assert.fail; 19 import static org.mockito.Mockito.times; 20 import static org.mockito.Mockito.verify; 21 import static org.mockito.Mockito.when; 22 23 import android.app.Dialog; 24 import android.app.Fragment; 25 26 import com.android.settings.testutils.SettingsRobolectricTestRunner; 27 28 import org.junit.Before; 29 import org.junit.Test; 30 import org.junit.runner.RunWith; 31 import org.mockito.Mock; 32 import org.mockito.MockitoAnnotations; 33 import org.robolectric.RuntimeEnvironment; 34 35 @RunWith(SettingsRobolectricTestRunner.class) 36 public class SettingsDialogFragmentTest { 37 38 private static final int DIALOG_ID = 15; 39 40 @Mock 41 private DialogCreatableFragment mDialogCreatable; 42 private SettingsPreferenceFragment.SettingsDialogFragment mDialogFragment; 43 44 @Before 45 public void setUp() { 46 MockitoAnnotations.initMocks(this); 47 } 48 49 @Test 50 public void testGetMetrics_shouldGetMetricFromDialogCreatable() { 51 when(mDialogCreatable.getDialogMetricsCategory(DIALOG_ID)).thenReturn(1); 52 53 mDialogFragment = 54 new SettingsPreferenceFragment.SettingsDialogFragment(mDialogCreatable, DIALOG_ID); 55 mDialogFragment.onAttach(RuntimeEnvironment.application); 56 mDialogFragment.getMetricsCategory(); 57 58 // getDialogMetricsCategory called in onAttach, and explicitly in test. 59 verify(mDialogCreatable, times(2)).getDialogMetricsCategory(DIALOG_ID); 60 } 61 62 @Test 63 public void testGetInvalidMetricsValue_shouldCrash() { 64 when(mDialogCreatable.getDialogMetricsCategory(DIALOG_ID)).thenReturn(-1); 65 66 try { 67 mDialogFragment = 68 new SettingsPreferenceFragment.SettingsDialogFragment(mDialogCreatable, DIALOG_ID); 69 mDialogFragment.onAttach(RuntimeEnvironment.application); 70 fail("Should fail with IllegalStateException"); 71 } catch (IllegalStateException e) { 72 // getDialogMetricsCategory called in constructor 73 verify(mDialogCreatable).getDialogMetricsCategory(DIALOG_ID); 74 return; 75 } 76 } 77 78 public static class DialogCreatableFragment extends Fragment implements DialogCreatable { 79 80 @Override 81 public Dialog onCreateDialog(int dialogId) { 82 return null; 83 } 84 85 @Override 86 public int getDialogMetricsCategory(int dialogId) { 87 return 0; 88 } 89 } 90 } 91