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

The following are Jave code examples for showing how to use getInstrumentation() of the android.support.test.InstrumentationRegistry class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Demos   File: UiTest.java   View Source Code Vote up 6 votes
/**
 * 测试CollapsingToolbarLayout
 * 被测Demo下载地址:https://github.com/alidili/DesignSupportDemo
 *
 * @throws UiObjectNotFoundException
 */
public void testA() throws UiObjectNotFoundException {
    // 获取设备对象
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    UiDevice uiDevice = UiDevice.getInstance(instrumentation);
    // 获取上下文
    Context context = instrumentation.getContext();

    // 启动测试App
    Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.yang.designsupportdemo");
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);

    // 打开CollapsingToolbarLayout
    String resourceId = "com.yang.designsupportdemo:id/CollapsingToolbarLayout";
    UiObject collapsingToolbarLayout = uiDevice.findObject(new UiSelector().resourceId(resourceId));
    collapsingToolbarLayout.click();

    for (int i = 0; i < 5; i++) {
        // 向上移动
        uiDevice.swipe(uiDevice.getDisplayHeight() / 2, uiDevice.getDisplayHeight(),
                uiDevice.getDisplayHeight() / 2, uiDevice.getDisplayHeight() / 2, 10);

        // 向下移动
        uiDevice.swipe(uiDevice.getDisplayHeight() / 2, uiDevice.getDisplayHeight() / 2,
                uiDevice.getDisplayHeight() / 2, uiDevice.getDisplayHeight(), 10);
    }

    // 点击应用返回按钮
    UiObject back = uiDevice.findObject(new UiSelector().description("Navigate up"));
    back.click();

    // 点击设备返回按钮
    uiDevice.pressBack();
}
 
Example 2
Project: GitHub   File: TiPluginTest.java   View Source Code Vote up 6 votes
@Test
public void startTestActivity() throws Exception {
    final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();

    // start the activity for the first time
    final TestActivity activity = startTestActivity(instrumentation);

    // make sure the attached presenter filled the UI
    Espresso.onView(withId(R.id.helloworld_text))
            .check(matches(allOf(isDisplayed(), withText("Hello World 1"))));

    Espresso.onView(withId(R.id.fragment_helloworld_text))
            .check(matches(allOf(isDisplayed(), withText("Hello World 1"))));

    activity.finish();
}
 
Example 3
Project: GitHub   File: TiPluginTest.java   View Source Code Vote up 6 votes
/**
 * Tests the full Activity lifecycle. Guarantees every lifecycle method gets called
 */
@Test
public void testFullLifecycleIncludingConfigurationChange() throws Throwable {
    final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();

    // start the activity for the first time
    final TestActivity activity = startTestActivity(instrumentation);

    // make sure the attached presenter filled the UI
    Espresso.onView(withId(R.id.helloworld_text))
            .check(matches(allOf(isDisplayed(), withText("Hello World 1"))));
    Espresso.onView(withId(R.id.fragment_helloworld_text))
            .check(matches(allOf(isDisplayed(), withText("Hello World 1"))));

    // restart the activity
    rotateOrientation(activity);

    // assert the activity was bound to the presenter. The presenter should update the UI
    // correctly
    Espresso.onView(withId(R.id.helloworld_text))
            .check(matches(allOf(isDisplayed(), withText("Hello World 2"))));
    Espresso.onView(withId(R.id.fragment_helloworld_text))
            .check(matches(allOf(isDisplayed(), withText("Hello World 2"))));

    activity.finish();
}
 
Example 4
Project: firefox-tv   File: ScreenshotTest.java   View Source Code Vote up 6 votes
@Before
public void setUpScreenshots() {
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    targetContext = instrumentation.getTargetContext();
    device = UiDevice.getInstance(instrumentation);

    // Use this to switch between default strategy and HostScreencap strategy
    //Screengrab.setDefaultScreenshotStrategy(new UiAutomatorScreenshotStrategy());
    Screengrab.setDefaultScreenshotStrategy(new HostScreencapScreenshotStrategy(device));

    device.waitForIdle();
}
 
Example 5
Project: RNLearn_Project1   File: ReactIdleDetectionUtil.java   View Source Code Vote up 6 votes
private static void waitInner(ReactBridgeIdleSignaler idleSignaler, long timeToWait) {
  // TODO gets broken in gradle, do we need it?
  Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
  long startTime = SystemClock.uptimeMillis();
  boolean bridgeWasIdle = false;
  while (SystemClock.uptimeMillis() - startTime < timeToWait) {
    boolean bridgeIsIdle = idleSignaler.isBridgeIdle();
    if (bridgeIsIdle && bridgeWasIdle) {
      return;
    }
    bridgeWasIdle = bridgeIsIdle;
    long newTimeToWait = Math.max(1, timeToWait - (SystemClock.uptimeMillis() - startTime));
    idleSignaler.waitForIdle(newTimeToWait);
    instrumentation.waitForIdleSync();
  }
  throw new RuntimeException("Timed out waiting for bridge and UI idle!");
}
 
Example 6
Project: dagger-test-example   File: WeatherFragmentTest.java   View Source Code Vote up 6 votes
@Test
public void searchFragmentShouldCollectDisposablesAndReleaseThemInOnDestroy() {
    CompositeDisposable composite = new CompositeDisposable();
    decorate().searchFragmentSubcomponent().withCompositeDisposable(() -> composite);
    final MainActivity activity = rule.launchActivity(null);
    final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    instrumentation.runOnMainSync(() ->
    {
        ((ViewPager)activity.findViewById(R.id.container)).setCurrentItem(2);
        assertEquals(1, composite.size());
        activity.finish();
    });
    instrumentation.waitForIdleSync();
    SystemClock.sleep(500);
    assertTrue(composite.isDisposed());
}
 
Example 7
Project: RNLearn_Project1   File: ReactTestHelper.java   View Source Code Vote up 5 votes
public static ReactTestFactory getReactTestFactory() {
  Instrumentation inst = InstrumentationRegistry.getInstrumentation();
  if (!(inst instanceof ReactTestFactory)) {
    return new DefaultReactTestFactory();
  }

  return (ReactTestFactory) inst;
}
 
Example 8
Project: GitHub   File: WebpBitmapFactoryTest.java   View Source Code Vote up 5 votes
@Override
@Before
public void setUp() {
  mInstrumentation = InstrumentationRegistry.getInstrumentation();
  mWebpBitmapFactory = new WebpBitmapFactoryImpl();
  ImagePipelineConfig.Builder configBuilder =
      ImagePipelineConfig.newBuilder(mInstrumentation.getContext())
          .experiment().setWebpBitmapFactory(mWebpBitmapFactory);
  ImagePipelineFactory.initialize(configBuilder.build());
}
 
Example 9
Project: GitHub   File: WebpDecodingTest.java   View Source Code Vote up 5 votes
@Override
@Before
public void setUp() {
  mInstrumentation = InstrumentationRegistry.getInstrumentation();
  mWebpBitmapFactory = new WebpBitmapFactoryImpl();
  ImagePipelineConfig.Builder configBuilder =
      ImagePipelineConfig.newBuilder(mInstrumentation.getContext())
          .experiment().setWebpBitmapFactory(mWebpBitmapFactory);
  ImagePipelineFactory.initialize(configBuilder.build());
}
 
Example 10
Project: mobile-store   File: FileCompatTest.java   View Source Code Vote up 5 votes
@Before
public void setUp() {
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    File dir = getWriteableDir(instrumentation);
    sourceFile = SanitizedFile.knownSanitized(
            AssetUtils.copyAssetToDir(instrumentation.getContext(), "simpleIndex.jar", dir));
    destFile = new SanitizedFile(dir, "dest-" + UUID.randomUUID() + ".testproduct");
    assertFalse(destFile.exists());
    assertTrue(sourceFile.getAbsolutePath() + " should exist.", sourceFile.exists());
}
 
Example 11
Project: mobile-store   File: ApkVerifierTest.java   View Source Code Vote up 5 votes
@Before
public void setUp() {
    instrumentation = InstrumentationRegistry.getInstrumentation();
    File dir = FileCompatTest.getWriteableDir(instrumentation);
    assertTrue(dir.isDirectory());
    assertTrue(dir.canWrite());
    sdk14Apk = AssetUtils.copyAssetToDir(instrumentation.getContext(),
            "org.fdroid.permissions.sdk14.apk",
            dir
    );
    minMaxApk = AssetUtils.copyAssetToDir(instrumentation.getContext(),
            "org.fdroid.permissions.minmax.apk",
            dir
    );
    extendedPermissionsApk = AssetUtils.copyAssetToDir(instrumentation.getContext(),
            "org.fdroid.extendedpermissionstest.apk",
            dir
    );
    extendedPermsXml = AssetUtils.copyAssetToDir(instrumentation.getContext(),
            "extendedPerms.xml",
            dir
    );
    assertTrue(sdk14Apk.exists());
    assertTrue(minMaxApk.exists());
    assertTrue(extendedPermissionsApk.exists());
    assertTrue(extendedPermsXml.exists());
}
 
Example 12
Project: RNLearn_Project1   File: ReactTestHelper.java   View Source Code Vote up 5 votes
public static ReactTestFactory getReactTestFactory() {
  Instrumentation inst = InstrumentationRegistry.getInstrumentation();
  if (!(inst instanceof ReactTestFactory)) {
    return new DefaultReactTestFactory();
  }

  return (ReactTestFactory) inst;
}
 
Example 13
Project: bcg   File: MainActivityTest.java   View Source Code Vote up 5 votes
@Before
public void setUp() {
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    BcgTestApplication app = (BcgTestApplication) instrumentation.getTargetContext().getApplicationContext();
    ApplicationTestComponent component = (ApplicationTestComponent) BcgApplication.getComponent();

    // inject dagger
    component.inject(this);

    // clear user data before test
    stateManager.clearUser();

    // Set up the stub we want to return in the mock
    LoginResponse loginResponse = new LoginResponse(TEST_USER_ID, TEST_TOKEN);
    Response<LoginResponse> loginResult = Response.success(loginResponse);

    ProfileResponse profileResponse = new ProfileResponse(TEST_EMAIL, TEST_AVATAR);
    Response<ProfileResponse> profileResult = Response.success(profileResponse);

    expectedResult = ProfileModel.create(TEST_EMAIL, TEST_AVATAR);

    // Setup the mock
    when(api.login(eq(TEST_EMAIL), eq(TEST_PASSWORD)))
            .thenReturn(Observable.just(loginResult));
    when(api.getProfile(eq(TEST_TOKEN), eq(TEST_USER_ID)))
            .thenReturn(Observable.just(profileResult));
}
 
Example 14
Project: dagger-test-example   File: SimpleEspressoTest.java   View Source Code Vote up 5 votes
@Test
public void removesLocationUpdatesOnStop() throws Throwable {
    final MainActivity activity = rule.launchActivity(null);
    final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    instrumentation.runOnMainSync(() -> {
        instrumentation.callActivityOnPause(activity);
        verify(locationService, times(0)).removeUpdates();
        instrumentation.callActivityOnStop(activity);
        verify(locationService).removeUpdates();
    });
    instrumentation.waitForIdleSync();
}
 
Example 15
Project: DebugOverlay-Android   File: DebugOverlayInstrumentedTest.java   View Source Code Vote up 4 votes
Instrumentation getInstrumentation() {
    return InstrumentationRegistry.getInstrumentation();
}
 
Example 16
Project: dagger-test-example   File: SimpleEspressoTest.java   View Source Code Vote up 4 votes
TestWeatherApplication app() {
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    return (TestWeatherApplication) instrumentation.getTargetContext().getApplicationContext();
}
 
Example 17
Project: webtrekk-android-sdk   File: WebtrekkBaseSDKTest.java   View Source Code Vote up 4 votes
protected Instrumentation getInstrumentation(){
    return InstrumentationRegistry.getInstrumentation();
}
 
Example 18
Project: Blockly   File: BlocklyActivityTest.java   View Source Code Vote up 4 votes
@Before
public void setUp() {
    mInstrumentation = InstrumentationRegistry.getInstrumentation();
    mActivity = mActivityRule.getActivity();
}
 
Example 19
Project: mvvm-template   File: BaseTest.java   View Source Code Vote up 4 votes
protected Instrumentation getInstrumentation() {
    return InstrumentationRegistry.getInstrumentation();
}
 
Example 20
Project: mvp-core   File: ActivityLifecycleTestRule.java   View Source Code Vote up 3 votes
/**
 * Creates an {@link ActivityLifecycleTestRule} for the Activity under test.
 *
 * @param activityClass    The activity under test. This must be a class in the instrumentation
 *                         targetPackage specified in the AndroidManifest.xml
 * @param initialTouchMode true if the Activity should be placed into "touch mode" when started
 * @param launchActivity   true if the Activity should be launched once per
 *                         <a href="http://junit.org/javadoc/latest/org/junit/Test.html">
 *                         <code>Test</code></a> method. It will be launched before the first
 *                         <a href="http://junit.sourceforge.net/javadoc/org/junit/Before.html">
 *                         <code>Before</code></a> method, and terminated after the last
 *                         <a href="http://junit.sourceforge.net/javadoc/org/junit/After.html">
 *                         <code>After</code></a> method.
 */
public ActivityLifecycleTestRule(Class<T> activityClass, boolean initialTouchMode,
                        boolean launchActivity) {
    mActivityClass = activityClass;
    mInitialTouchMode = initialTouchMode;
    mLaunchActivity = launchActivity;
    mInstrumentation = InstrumentationRegistry.getInstrumentation();
}