Java Code Examples for android.support.test.InstrumentationRegistry#getInstrumentation()

The following examples show how to use android.support.test.InstrumentationRegistry#getInstrumentation() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProcessOwnerTest.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Test
public void testNavigation() throws Throwable {
    FragmentActivity firstActivity = setupObserverOnResume();
    Instrumentation.ActivityMonitor monitor = new Instrumentation.ActivityMonitor(
            NavigationTestActivitySecond.class.getCanonicalName(), null, false);
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    instrumentation.addMonitor(monitor);

    Intent intent = new Intent(firstActivity, NavigationTestActivitySecond.class);
    firstActivity.finish();
    firstActivity.startActivity(intent);

    FragmentActivity secondActivity = (FragmentActivity) monitor.waitForActivity();
    assertThat("Failed to navigate", secondActivity, notNullValue());
    checkProcessObserverSilent(secondActivity);
}
 
Example 2
Source File: SubjectViewerActivityTest.java    From android-galaxyzoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testStateDestroy() {
    final String TEST_ITEM_ID = "test123456789";
    mActivity.setItemId(TEST_ITEM_ID);
    mActivity.finish();

    // Based on this:
    // http://stackoverflow.com/a/33213279/1123654
    final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    instrumentation.runOnMainSync(new Runnable() {
        @Override
        public void run() {
            mActivity.recreate();
        }
    });

    assertEquals(TEST_ITEM_ID, mActivity.getItemId());

    //TODO: Do something like this too:
    //onView(withText("a string depending on XXX value")).check(doesNotExist())
}
 
Example 3
Source File: ClassifyActivityTest.java    From android-galaxyzoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testStateDestroy() {
    final String TEST_ITEM_ID = "test123456789";
    mActivity.setItemId(TEST_ITEM_ID);
    mActivity.finish();

    // Based on this:
    // http://stackoverflow.com/a/33213279/1123654
    final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    instrumentation.runOnMainSync(new Runnable() {
        @Override
        public void run() {
            mActivity.recreate();
        }
    });

    assertEquals(TEST_ITEM_ID, mActivity.getItemId());

    //TODO: Do something like this too:
    //onView(withText("a string depending on XXX value")).check(doesNotExist())
}
 
Example 4
Source File: LoginActivityTest.java    From android-galaxyzoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testStateDestroy() {
    //final String TEST_SOMETHING = "test123456789";
    //TODO: mActivity.setSomething();
    mActivity.finish();

    // Based on this:
    // http://stackoverflow.com/a/33213279/1123654
    final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    instrumentation.runOnMainSync(new Runnable() {
        @Override
        public void run() {
            mActivity.recreate();
        }
    });

    //TODOassertEquals(TEST_SOMETHING, mActivity.getSomething());

    //TODO: Do something like this too:
    //onView(withText("a string depending on XXX value")).check(doesNotExist())
}
 
Example 5
Source File: QuestionHelpActivityTest.java    From android-galaxyzoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testStateDestroy() {
    final String TEST_QUESTION_ID = "sloan-999";
    mActivity.setQuestionId(TEST_QUESTION_ID);
    mActivity.finish();

    // Based on this:
    // http://stackoverflow.com/a/33213279/1123654
    final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    instrumentation.runOnMainSync(new Runnable() {
        @Override
        public void run() {
            mActivity.recreate();
        }
    });

    assertEquals(TEST_QUESTION_ID, mActivity.getQuestionId());

    //TODO: Do something like this too:
    //onView(withText("a string depending on XXX value")).check(doesNotExist())
}
 
Example 6
Source File: BaseTest.java    From friendspell with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
  FriendSpellApplication app
      = (FriendSpellApplication) instrumentation.getTargetContext().getApplicationContext();
  TestComponent component = (TestComponent) app.component();
  component.inject(this);

  Mockito.reset(googleApiClientBridge);

  databaseApi.clear();

  SharedPreferences.Editor editor = pref.edit();
  editor.clear();
  editor.apply();
}
 
Example 7
Source File: ImmediateNavigationTest.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Test
public void testNavigateInOnResume() throws Throwable {
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    Intent intent = new Intent(instrumentation.getContext(),
            ImmediateNavigationActivity.class);

    final ImmediateNavigationActivity activity = mActivityRule.launchActivity(intent);
    instrumentation.waitForIdleSync();
    NavController navController = activity.getNavController();
    assertThat(navController.getCurrentDestination().getId(), is(R.id.deep_link_test));
}
 
Example 8
Source File: TestUtils.java    From android-galaxyzoo with GNU General Public License v3.0 5 votes vote down vote up
static void setTheme() {
    //Avoid this exception:
    //java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
    final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    final Context context = instrumentation.getTargetContext();
    context.setTheme(R.style.AppTheme);

}
 
Example 9
Source File: MainActivityDaggerTest.java    From fyber_mobile_offers with MIT License 5 votes vote down vote up
@Before
public void setUp() {
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    MockFyberApplication app = (MockFyberApplication) instrumentation.getTargetContext().getApplicationContext();
    TestApplicationComponent component = (TestApplicationComponent) app.getComponent();
    component.inject(this);

    // Set up the stub we want to return in the mock
    Offer offer = new Offer();
    offer.setTitle(TEST_OFFER_TITLE);
    offer.setTeaser(TEST_OFFER_TEASER);
    offer.setPayout(TEST_OFFER_PAYLOAD);

    expectedOffers = new Offer[1];
    expectedOffers[0] = offer;

    // put the test offer in a test api result
    expectedResult = new OfferResponse();
    expectedResult.setOffers(expectedOffers);
    expectedResult.setPages(1);
    expectedResult.setCode(Constants.CODE_OK);

    // Set up the mock
    when(api.getOffers(any(String.class), any(Integer.class), any(String.class), any(String.class), any(String.class), any(Long.class), any(String.class), any(String.class), any(Boolean.class), any(String.class), any(String.class), any(Integer.class), any(Integer.class), any(String.class)))
            .thenReturn(Observable.just(expectedResult));

    when(valueManager.isConnected()).thenReturn(true);
    when(valueManager.getAdId()).thenReturn("adId");
    when(valueManager.getAdIdEnabled()).thenReturn(false);
    when(valueManager.getApplicationId()).thenReturn(123);
    when(valueManager.getApiKey()).thenReturn("apiKey");
}
 
Example 10
Source File: TestMainActivityWithRobotium.java    From vb-android-app-quality with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();
    mSolo = new Solo(InstrumentationRegistry.getInstrumentation(), mActivityRule.getActivity());
    mEditText = (EditText) mSolo.getView(R.id.editTextDigits);
    mButtonSendPI = (Button) mSolo.getView(R.id.buttonSendPi);
    mButtonCompute = (Button) mSolo.getView(R.id.buttonCompute);
    mButtonShare = (Button) mSolo.getView(R.id.buttonShareResult);
}
 
Example 11
Source File: ReactTestHelper.java    From react-native-GPay with MIT License 5 votes vote down vote up
public static ReactTestFactory getReactTestFactory() {
  Instrumentation inst = InstrumentationRegistry.getInstrumentation();
  if (!(inst instanceof ReactTestFactory)) {
    return new DefaultReactTestFactory();
  }

  return (ReactTestFactory) inst;
}
 
Example 12
Source File: ActivityHelperTest.java    From OPFIab with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws InterruptedException {
    Thread.sleep(WAIT_TEST_MANAGER);
    instrumentation = InstrumentationRegistry.getInstrumentation();
    activity = testRule.getActivity();
    uiDevice = UiDevice.getInstance(instrumentation);
}
 
Example 13
Source File: ViewModelTest.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private ViewModelActivity recreateActivity() throws Throwable {
    Instrumentation.ActivityMonitor monitor = new Instrumentation.ActivityMonitor(
            ViewModelActivity.class.getCanonicalName(), null, false);
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    instrumentation.addMonitor(monitor);
    final ViewModelActivity previous = mActivityRule.getActivity();
    mActivityRule.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            previous.recreate();
        }
    });
    ViewModelActivity result;

    // this guarantee that we will reinstall monitor between notifications about onDestroy
    // and onCreate
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (monitor) {
        do {
            // the documentation says "Block until an Activity is created
            // that matches this monitor." This statement is true, but there are some other
            // true statements like: "Block until an Activity is destroyed" or
            // "Block until an Activity is resumed"...

            // this call will release synchronization monitor's monitor
            result = (ViewModelActivity) monitor.waitForActivityWithTimeout(4000);
            if (result == null) {
                throw new RuntimeException("Timeout. Failed to recreate an activity");
            }
        } while (result == previous);
    }
    return result;
}
 
Example 14
Source File: RepositoriesInstrumentedTest.java    From flowless with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    Espresso.registerIdlingResources(EspressoIdlingResource.getIdlingResource());
    mainPage = new MainPage();
    repositoriesPage = new RepositoriesPage();
    mainActivityActivityTestRule.launchActivity(null);
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    MainActivity mainActivity = mainActivityActivityTestRule.getActivity();
    instrumentation.runOnMainSync(() -> {
        Flow.get(mainActivity.getBaseContext()).setHistory(History.single(RepositoriesKey.create()), Direction.REPLACE);
    });
}
 
Example 15
Source File: HelperSteps.java    From CleanGUITestArchitecture with MIT License 5 votes vote down vote up
private static void grantWritePermissionsForScreenshots() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        try {
            Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
            String appPackage = getTargetContext().getPackageName();
            instrumentation.getUiAutomation().executeShellCommand("pm grant " + appPackage
                + " android.permission.READ_EXTERNAL_STORAGE");
            instrumentation.getUiAutomation().executeShellCommand("pm grant " + appPackage
                + " android.permission.WRITE_EXTERNAL_STORAGE");
        } catch (Exception e) {
            throw new RuntimeException(
                "Exception while granting external storage access to application apk", e);
        }
    }
}
 
Example 16
Source File: GlobalEventListener.java    From za-Farmer with MIT License 4 votes vote down vote up
private void initListener() {

        Instrumentation mInstrumentation = InstrumentationRegistry.getInstrumentation();
        mInstrumentation.getUiAutomation().setOnAccessibilityEventListener(
                new UiAutomation.OnAccessibilityEventListener() {
                    @Override
                    public void onAccessibilityEvent(AccessibilityEvent event) {
                        try {
                            final int eventType = event.getEventType();
                            //处理权限框
                            if (eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && permissionsWindowHandler) {


                                //package 符合
                                final String packageName = event.getPackageName().toString();
                                if (!Pattern.matches(packages, packageName)) {
                                    return;
                                }


                                //部分机型无法获取全部的Texts,故下面部分进行注释
//                                String btnText = null;
//                                final List<CharSequence> texts = event.getText();
//                                for (CharSequence text : texts) {
//                                    if (Pattern.matches(allowButton, text)) {
//                                        btnText = text.toString();
//                                        break;
//                                    }
//                                }
//
//                                //btnText 符合
//                                if (btnText == null) {
//                                    return;
//                                }
//
//                                //文本日志
//                                LogUtils.getInstance().info("permissions window: package " + packageName
//                                        + ",text " + texts);


                                BySelector permissionsSelector = By.pkg(packageName).text(Pattern.compile(allowButton));
                                UiObject2 obj = uiDevice.findObjectOnce(permissionsSelector);
                                if (obj!= null) {

                                    //截图日志
                                    LogUtils.getInstance().infoScreenshot(new RectCanvasHandler(obj.getVisibleBounds()));
                                    obj.click();

                                }

                            } else if (eventType == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {
                                //判断是否是通知事件
                                Parcelable parcelable = event.getParcelableData();
                                //如果不是下拉通知栏消息,则为其它通知信息,包括Toast
                                if (!(parcelable instanceof Notification)) {
                                    List <CharSequence> messageList = event.getText();
                                    for (CharSequence toast_Message : messageList) {
                                        if (!TextUtils.isEmpty(toast_Message)) {
                                            for (IGlobalEventChecker toastChecker : toastCheckerSet) {
                                                toastChecker.check(toast_Message.toString());
                                            }
                                            return;
                                        }
                                    }
                                }
                            }
                        } catch (Exception ex) {
                            LogUtils.getInstance().error(ex);
                        }
                    }
                }
        );
    }
 
Example 17
Source File: AdvancedHelperTest.java    From OPFIab with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    activity = testRule.getActivity();
    setupDexmaker();
    instrumentation = InstrumentationRegistry.getInstrumentation();
}
 
Example 18
Source File: ActivityRule.java    From u2020-mvp with Apache License 2.0 4 votes vote down vote up
private Instrumentation fetchInstrumentation() {
  Instrumentation result = instrumentation;
  return result != null ? result
      : (instrumentation = InstrumentationRegistry.getInstrumentation());
}
 
Example 19
Source File: BaseTest.java    From mvvm-template with GNU General Public License v3.0 4 votes vote down vote up
protected Instrumentation getInstrumentation() {
    return InstrumentationRegistry.getInstrumentation();
}
 
Example 20
Source File: FragmentHelperTest.java    From OPFIab with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    instrumentation = InstrumentationRegistry.getInstrumentation();
    activity = testRule.getActivity();
    uiDevice = UiDevice.getInstance(instrumentation);
}