Java Code Examples for android.app.Instrumentation

The following are top voted examples for showing how to use android.app.Instrumentation. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: VirtualAPK   File: LoadedPlugin.java   View source code 7 votes vote down vote up
private Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {
    if (null != this.mApplication) {
        return this.mApplication;
    }

    String appClass = this.mPackage.applicationInfo.className;
    if (forceDefaultAppClass || null == appClass) {
        appClass = "android.app.Application";
    }

    try {
        this.mApplication = instrumentation.newApplication(this.mClassLoader, appClass, this.getPluginContext());
        instrumentation.callApplicationOnCreate(this.mApplication);
        return this.mApplication;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 2
Project: Demos   File: UiTest.java   View source code 6 votes vote down vote up
/**
 * 测试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 3
Project: Demos   File: UiTest.java   View source code 6 votes vote down vote up
/**
 * 滑动界面,打开About phone选项
 * 测试环境为标准Android 7.1.1版本,不同设备控件查找方式会有不同
 *
 * @throws UiObjectNotFoundException
 */
public void testB() throws UiObjectNotFoundException {
    // 获取设备对象
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    UiDevice uiDevice = UiDevice.getInstance(instrumentation);
    // 获取上下文
    Context context = instrumentation.getContext();

    // 点击Settings按钮
    UiObject uiObject = uiDevice.findObject(new UiSelector().description("Settings"));
    uiObject.click();

    // 滑动列表到最后,点击About phone选项
    UiScrollable settings = new UiScrollable(new UiSelector().className("android.support.v7.widget.RecyclerView"));
    UiObject about = settings.getChildByText(new UiSelector().className("android.widget.LinearLayout"), "About phone");
    about.click();

    // 点击设备返回按钮
    uiDevice.pressBack();
    uiDevice.pressBack();
}
 
Example 4
Project: GitHub   File: TiPluginTest.java   View source code 6 votes vote down vote up
@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 5
Project: GitHub   File: TiPluginTest.java   View source code 6 votes vote down vote up
/**
 * 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 6
Project: DebugOverlay-Android   File: DebugOverlayInstrumentedTest.java   View source code 6 votes vote down vote up
void waitForOverlay(long millis) {
    if (!testSystemLayer()) {
        Instrumentation.ActivityMonitor monitor = new Instrumentation.ActivityMonitor(MainActivity.class.getCanonicalName(),
                null, false);
        getInstrumentation().addMonitor(monitor);
        getActivityRule().launchActivity(new Intent(getApplication(), MainActivity.class));
        try {
            monitor.waitForActivityWithTimeout(5000);
        } finally {
            getInstrumentation().removeMonitor(monitor);
        }
    }
    try {
        Thread.currentThread().sleep(millis);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 7
Project: android-apkbox   File: HookActivityInstrumentationHnadler.java   View source code 6 votes vote down vote up
public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Fragment fragment,
                                        Intent intent, int requestCode, Bundle options) {
    try {
        Intent targetIntent = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
            targetIntent = HookActivity_Intent.modify(fragment.getActivity(), intent);
        }
        if (targetIntent == null) {
            targetIntent = intent;
        }
        ApkMethod method = new ApkMethod(Instrumentation.class, mInstrumentation, "execStartActivity", Context.class, IBinder.class, IBinder.class, Fragment.class, Intent.class, int.class, Bundle.class);
        return method.invoke(who, contextThread, token, fragment, targetIntent, requestCode, options);
    } catch (Exception error) {
        ApkLogger.get().error("execStartActivity Exception", error);
        return null;
    }
}
 
Example 8
Project: pracler   File: PlayerActivity.java   View source code 6 votes vote down vote up
/** IMAGE PROCESSING FUNCTION */


    public void openMenu()
    {
        new Thread(new Runnable()
        {
            public void run()
            {
                KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU);
                new Instrumentation().sendKeySync(event);
                KeyEvent event2 = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MENU);
                new Instrumentation().sendKeySync(event2);
            }
        }).start();
    }
 
Example 9
Project: adyen-android   File: EspressoTestUtils.java   View source code 6 votes vote down vote up
private static <X> X callOnMainSync(Instrumentation instrumentation, final Callable<X> callable)
        throws Exception {
    final AtomicReference<X> retAtomic = new AtomicReference<>();
    final AtomicReference<Throwable> exceptionAtomic = new AtomicReference<>();
    instrumentation.runOnMainSync(new Runnable() {
        @Override
        public void run() {
            try {
                retAtomic.set(callable.call());
            } catch (Throwable e) {
                exceptionAtomic.set(e);
            }
        }
    });
    final Throwable exception = exceptionAtomic.get();
    if (exception != null) {
        Throwables.propagateIfInstanceOf(exception, Exception.class);
        Throwables.propagate(exception);
    }
    return retAtomic.get();
}
 
Example 10
Project: adyen-android   File: EspressoTestUtils.java   View source code 6 votes vote down vote up
private static boolean closeActivity(Instrumentation instrumentation) throws Exception {
    final Boolean activityClosed = callOnMainSync(instrumentation, new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            final Set<Activity> activities = getActivitiesInStages(Stage.RESUMED,
                    Stage.STARTED, Stage.PAUSED, Stage.STOPPED, Stage.CREATED);
            activities.removeAll(getActivitiesInStages(Stage.DESTROYED));
            if (activities.size() > 0) {
                final Activity activity = activities.iterator().next();
                activity.finish();
                return true;
            } else {
                return false;
            }
        }
    });
    if (activityClosed) {
        instrumentation.waitForIdleSync();
    }
    return activityClosed;
}
 
Example 11
Project: mobile-store   File: FileCompatTest.java   View source code 6 votes vote down vote up
/**
 * Prefer internal over external storage, because external tends to be FAT filesystems,
 * which don't support symlinks (which we test using this method).
 */
public static File getWriteableDir(Instrumentation instrumentation) {
    Context context = instrumentation.getContext();
    Context targetContext = instrumentation.getTargetContext();

    File[] dirsToTry = new File[]{
            context.getCacheDir(),
            context.getFilesDir(),
            targetContext.getCacheDir(),
            targetContext.getFilesDir(),
            context.getExternalCacheDir(),
            context.getExternalFilesDir(null),
            targetContext.getExternalCacheDir(),
            targetContext.getExternalFilesDir(null),
            Environment.getExternalStorageDirectory(),
    };

    return getWriteableDir(dirsToTry);
}
 
Example 12
Project: civify-app   File: CreateIssueActivityTest.java   View source code 6 votes vote down vote up
private static void pickGalleryPhoto() throws IOException {

        Drawable drawable = getTargetContext().getResources().getDrawable(R.drawable.upc_library);
        Bitmap bmp = drawableToBitmap(drawable);

        File storageDir =
                new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                        "Camera");
        File image = File.createTempFile("testImage", ".jpg", storageDir);

        FileOutputStream out = new FileOutputStream(image);
        bmp.compress(CompressFormat.JPEG, 100, out);

        // Build a result to return from the Camera app
        Intent resultData = new Intent();
        resultData.setData(Uri.fromFile(image));
        Instrumentation.ActivityResult result =
                new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);

        // Stub out the Camera. When an intent is sent to the Camera, this tells Espresso to respond
        // with the ActivityResult we just created
        intending(not(isInternal())).respondWith(result);
        intended(not(isInternal()));
    }
 
Example 13
Project: StallBuster   File: StallBuster.java   View source code 6 votes vote down vote up
private void hookStartActivity() {
    try {
        Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
        Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread");
        currentActivityThreadMethod.setAccessible(true);
        Object currentActivityThread = currentActivityThreadMethod.invoke(null);

        Field mInstrumentationField = activityThreadClass.getDeclaredField("mInstrumentation");
        mInstrumentationField.setAccessible(true);
        Instrumentation mInstrumentation = (Instrumentation) mInstrumentationField.get(currentActivityThread);
        Instrumentation myInstrumentation = new InstrumentationProxy(mInstrumentation, mHandler);
        mInstrumentationField.set(currentActivityThread, myInstrumentation);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 14
Project: ExoPlayer-Offline   File: FakeExtractorOutput.java   View source code 6 votes vote down vote up
/**
 * Asserts that dump of this {@link FakeExtractorOutput} is equal to expected dump which is read
 * from {@code dumpFile}.
 *
 * <p>If assertion fails because of an intended change in the output or a new dump file needs to
 * be created, set {@link #WRITE_DUMP} flag to true and run the test again. Instead of assertion,
 * actual dump will be written to {@code dumpFile}. This new dump file needs to be copied to the
 * project, {@code library/src/androidTest/assets} folder manually.
 */
public void assertOutput(Instrumentation instrumentation, String dumpFile) throws IOException {
  String actual = new Dumper().add(this).toString();

  if (WRITE_DUMP) {
    File directory = instrumentation.getContext().getExternalFilesDir(null);
    File file = new File(directory, dumpFile);
    file.getParentFile().mkdirs();
    PrintWriter out = new PrintWriter(file);
    out.print(actual);
    out.close();
  } else {
    String expected = TestUtil.getString(instrumentation, dumpFile);
    Assert.assertEquals(dumpFile, expected, actual);
  }
}
 
Example 15
Project: RNLearn_Project1   File: ReactIdleDetectionUtil.java   View source code 6 votes vote down vote up
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 16
Project: Sherlock   File: CrashListActivityTest.java   View source code 6 votes vote down vote up
@Test
public void shouldOpenCrashDetails() throws Exception {
  SherlockDatabaseHelper database = new SherlockDatabaseHelper(InstrumentationRegistry.getTargetContext());
  String placeOfCrash1 = "com.singhajit.Sherlock:10";
  String stackTrace1 = "Crash 1 details";

  Crash crash1 = new Crash(placeOfCrash1, "Reason of crash", stackTrace1);
  int crashId = database.insertCrash(CrashRecord.createFrom(crash1));

  rule.launchActivity(null);

  intending(anyIntent()).respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, new Intent()));
  onView(withRecyclerView(R.id.crash_list, 0)).perform(click());
  intended(allOf(
      hasComponent(CrashActivity.class.getName()),
      hasExtra(CrashActivity.CRASH_ID, crashId)));
}
 
Example 17
Project: MagicBox   File: Secy.java   View source code 6 votes vote down vote up
@SuppressLint("PrivateApi")
    public void hookInstrumentation() {

        final String msg_fail = "cannot enable global delegate mode";
        try {
            Class<?> activityThreadClz = Class.forName(HookHelper.NAME_ACTIVITY_THREAD);
            Object owner = HookHelper.getCurrentActivityThreadObject();
//            Instrumentation mBase = HookHelper.getOriginalInstrumentation(activityThreadClz, owner);
            Field field = HookHelper.getOriginalInstrumentationField(activityThreadClz);

//            Instrumentation proxy = InstrumentationProxy.create(application);
            Instrumentation proxy = new MagicBoxInstrumentation();
//            if (owner == null || field == null||proxy == null)  ignore check

            HookHelper.hookInstrumentation(owner, field, proxy);

        } catch (Exception e) {
            e.printStackTrace();
            MagicBox.getLogger().error("[globalDelegateMode]", msg_fail);
        }
    }
 
Example 18
Project: VirtualAPK   File: VAInstrumentation.java   View source code 6 votes vote down vote up
private ActivityResult realExecStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    ActivityResult result = null;
    try {
        Class[] parameterTypes = {Context.class, IBinder.class, IBinder.class, Activity.class, Intent.class,
        int.class, Bundle.class};
        result = (ActivityResult)ReflectUtil.invoke(Instrumentation.class, mBase,
                "execStartActivity", parameterTypes,
                who, contextThread, token, target, intent, requestCode, options);
    } catch (Exception e) {
        if (e.getCause() instanceof ActivityNotFoundException) {
            throw (ActivityNotFoundException) e.getCause();
        }
        e.printStackTrace();
    }

    return result;
}
 
Example 19
Project: VirtualAPK   File: PluginManager.java   View source code 6 votes vote down vote up
private void hookInstrumentationAndHandler() {
    try {
        Instrumentation baseInstrumentation = ReflectUtil.getInstrumentation(this.mContext);
        if (baseInstrumentation.getClass().getName().contains("lbe")) {
            // reject executing in paralell space, for example, lbe.
            System.exit(0);
        }

        final VAInstrumentation instrumentation = new VAInstrumentation(this, baseInstrumentation);
        Object activityThread = ReflectUtil.getActivityThread(this.mContext);
        ReflectUtil.setInstrumentation(activityThread, instrumentation);
        ReflectUtil.setHandlerCallback(this.mContext, instrumentation);
        this.mInstrumentation = instrumentation;
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 20
Project: mvp-core   File: ActivityLifecycleTestRule.java   View source code 6 votes vote down vote up
public void recreateCurrentActivity() {
    if( mActivity != null )
    {
        final Instrumentation.ActivityMonitor monitor =
            new Instrumentation.ActivityMonitor(mActivity.getClass().getName(), null, false);
        mInstrumentation.addMonitor(monitor);

        mInstrumentation.runOnMainSync(new Runnable()
        {
            @Override
            public void run()
            {
                mActivity.recreate();
            }
        });
        afterActivityFinished();
        mInstrumentation.waitForIdleSync();

        beforeActivityLaunched();
        //noinspection unchecked
        mActivity = checkNotNull((T) monitor.waitForActivity(), "current activity shouldn't be null!");
        afterActivityLaunched();

        mInstrumentation.removeMonitor(monitor);
    }
}
 
Example 21
Project: webtrekk-android-sdk   File: WebtrekkBaseSDKTest.java   View source code 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
static public void finishActivitySync(Activity activity, Instrumentation instrumentation, boolean doFinish)
{
    if (doFinish)
        activity.finish();
    //give activity one minute to finish
    long currentTime = System.currentTimeMillis();
    boolean finishTimeout = false;
    int activityHash = activity.hashCode();
    boolean isDestroyed = false;

    while (!isDestroyed && !finishTimeout) {
        instrumentation.waitForIdleSync();
        finishTimeout = (System.currentTimeMillis() - currentTime) > 140000;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            isDestroyed = activity.isDestroyed();
        }else {
            isDestroyed = (Boolean)callMethod(null, activity.getWindow(), "isDestroyed", null);
        }
    }

    if (finishTimeout) {
        WebtrekkLogging.log("finishActivitySync: finished by timeout. Hash:" + activityHash);
    }
}
 
Example 22
Project: androidnative.pri   File: ExampleActivityTest.java   View source code 6 votes vote down vote up
private void startActivity() {
    if (launched)
        return;

    Instrumentation instrumentation = getInstrumentation();
    Intent intent = new Intent(getInstrumentation()
            .getTargetContext(), AndroidNativeActivity.class);
    intent.setFlags(intent.getFlags()  | Intent.FLAG_ACTIVITY_NEW_TASK);

    mActivity = instrumentation.startActivitySync(intent);
    launched = true;
    
    instrumentation.waitForIdleSync();
    sleep(5000);
}
 
Example 23
Project: dagger-test-example   File: WeatherFragmentTest.java   View source code 6 votes vote down vote up
@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 24
Project: firefox-tv   File: ScreenshotTest.java   View source code 6 votes vote down vote up
@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 25
Project: DroidPlugin   File: InstrumentationHook.java   View source code 6 votes vote down vote up
@Override
protected void onInstall(ClassLoader classLoader) throws Throwable {

    Object target = ActivityThreadCompat.currentActivityThread();
    Class ActivityThreadClass = ActivityThreadCompat.activityThreadClass();

     /*替换ActivityThread.mInstrumentation,拦截组件调度消息*/
    Field mInstrumentationField = FieldUtils.getField(ActivityThreadClass, "mInstrumentation");
    Instrumentation mInstrumentation = (Instrumentation) FieldUtils.readField(mInstrumentationField, target);
    if (!PluginInstrumentation.class.isInstance(mInstrumentation)) {
        PluginInstrumentation pit = new PluginInstrumentation(mHostContext, mInstrumentation);
        pit.setEnable(isEnable());
        mPluginInstrumentations.add(pit);
        FieldUtils.writeField(mInstrumentationField, target, pit);
        Log.i(TAG, "Install Instrumentation Hook old=%s,new=%s", mInstrumentationField, pit);
    } else {
        Log.i(TAG, "Instrumentation has installed,skip");
    }
}
 
Example 26
Project: cat-is-a-dog   File: AddHabitEventActivityTest.java   View source code 6 votes vote down vote up
@Test
public void addImage() {
    Intent resultData = new Intent();
    Bitmap icon = BitmapFactory.decodeResource(getInstrumentation().getContext().getResources(),
            R.drawable.mock_camera_image);
    resultData.putExtra("data", icon);
    Instrumentation.ActivityResult result =
            new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);

    intending(not(isInternal())).respondWith(result);

    Espresso.closeSoftKeyboard();

    onView(withId(R.id.imageOpacityOverlay)).perform(click());
    onView(withId(R.id.imageOpacityOverlay)).check(matches(not(isDisplayed())));

    onView(withId(R.id.imageDelete)).perform(click());
    onView(withId(R.id.imageOpacityOverlay)).check(matches(isDisplayed()));
}
 
Example 27
Project: TPlayer   File: HookHelper.java   View source code 6 votes vote down vote up
public static void attachContext() throws Exception{
    // 先获取到当前的ActivityThread对象
    Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
    Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread");
    currentActivityThreadMethod.setAccessible(true);
    //currentActivityThread是一个static函数所以可以直接invoke,不需要带实例参数
    Object currentActivityThread = currentActivityThreadMethod.invoke(null);

    // 反射拿到原始的 mInstrumentation字段
    Field mInstrumentationField = activityThreadClass.getDeclaredField("mInstrumentation");
    mInstrumentationField.setAccessible(true);
    Instrumentation mInstrumentation = (Instrumentation) mInstrumentationField.get(currentActivityThread);

    // 创建代理对象
    Instrumentation proxyInstrumentation = new MyProxyInstrumentation(mInstrumentation);

    // 偷梁换柱
    mInstrumentationField.set(currentActivityThread, proxyInstrumentation);
}
 
Example 28
Project: AndroidTestingTutorial   File: GalleryPickerTesting.java   View source code 6 votes vote down vote up
@Test
public void checkTextOnScreen() {
    //to check view on screen

    Intent resultData = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    resultData.setData(Uri.parse(("content://media/external/images/media/337663")));
    Matcher<Intent> MediaPickIntent = allOf(hasAction(Intent.ACTION_PICK), hasData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
    Intents.init();
    intending(MediaPickIntent).respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData));

    onView(withText("Gallery")).perform(click());
    onView(withId(R.id.btnGalleryPick)).perform(click());
    intended(MediaPickIntent);
    //To check the image pick works or not
    try{
        Thread.sleep(4500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 29
Project: GitHub   File: DbTest.java   View source code 5 votes vote down vote up
/** Returns a prepared application with the onCreate method already called. */
public <T extends Application> T createApplication(Class<T> appClass) {
    assertNull("Application already created", application);
    T app;
    try {
        app = (T) Instrumentation.newApplication(appClass, getContext());
    } catch (Exception e) {
        throw new RuntimeException("Could not create application " + appClass, e);
    }
    app.onCreate();
    application = app;
    return app;
}
 
Example 30
Project: DebugOverlay-Android   File: DebugOverlayInstrumentedTest.java   View source code 5 votes vote down vote up
@Test
public void startSecondActivity() {
    getInstrumentation().runOnMainSync(new Runnable() {
        @Override
        public void run() {
            debugOverlay = new DebugOverlay.Builder(getApplication())
                    .allowSystemLayer(testSystemLayer())
                    .build();
            debugOverlay.install();
        }
    });

    waitForOverlay();

    Instrumentation.ActivityMonitor monitor = new Instrumentation.ActivityMonitor(ScrollingActivity.class.getCanonicalName(),
            null, false);
    getInstrumentation().addMonitor(monitor);
    try {
        onView(withId(com.ms_square.debugoverlay.sample.R.id.fab)).perform(click());
        Activity nextActivity = monitor.waitForActivityWithTimeout(5000);
        assertThat(nextActivity, Matchers.is(Matchers.notNullValue()));

        takeActivityScreenShot(nextActivity);

        nextActivity.finish();
    } finally {
        getInstrumentation().removeMonitor(monitor);
    }
}
 
Example 31
Project: adyen-android   File: EspressoTestUtils.java   View source code 5 votes vote down vote up
public static void closeAllActivities(Instrumentation instrumentation) throws Exception {
    int i = 0;
    while (closeActivity(instrumentation)) {
        if (i++ > NUMBER_OF_RETRIES) {
            throw new AssertionError("Limit of retries excesses");
        }
        Thread.sleep(200);
    }
}
 
Example 32
Project: mobile-store   File: FileCompatTest.java   View source code 5 votes vote down vote up
@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 33
Project: RNLearn_Project1   File: ReactTestHelper.java   View source code 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 34
Project: Dominate   File: PpwButtonService.java   View source code 5 votes vote down vote up
private void handlePlay() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Instrumentation inst = new Instrumentation();
                inst.sendKeyDownUpSync(KeyEvent.KEYCODE_HEADSETHOOK);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}
 
Example 35
Project: Dominate   File: PpwButtonService.java   View source code 5 votes vote down vote up
private void handleNext() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Instrumentation inst = new Instrumentation();
                inst.sendKeyDownUpSync(KeyEvent.KEYCODE_HEADSETHOOK);
                inst.sendKeyDownUpSync(KeyEvent.KEYCODE_HEADSETHOOK);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}
 
Example 36
Project: ExoPlayer-Offline   File: TestUtil.java   View source code 5 votes vote down vote up
public static boolean assetExists(Instrumentation instrumentation, String fileName)
    throws IOException {
  int i = fileName.lastIndexOf('/');
  String path = i >= 0 ? fileName.substring(0, i) : "";
  String file = i >= 0 ? fileName.substring(i + 1) : fileName;
  return Arrays.asList(instrumentation.getContext().getResources().getAssets().list(path))
      .contains(file);
}
 
Example 37
Project: RNLearn_Project1   File: ReactTestHelper.java   View source code 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 38
Project: ExoPlayer-Offline   File: TestUtil.java   View source code 5 votes vote down vote up
/**
 * Asserts that {@code extractor} consumes {@code sampleFile} successfully and its output equals
 * to a prerecorded output dump file with the name {@code sampleFile} + "{@value
 * #DUMP_EXTENSION}". If {@code simulateUnknownLength} is true and {@code sampleFile} + "{@value
 * #UNKNOWN_LENGTH_EXTENSION}" exists, it's preferred.
 *
 * @param extractor The {@link Extractor} to be tested.
 * @param sampleFile The path to the input sample.
 * @param fileData Content of the input file.
 * @param instrumentation To be used to load the sample file.
 * @param simulateIOErrors If true simulates IOErrors.
 * @param simulateUnknownLength If true simulates unknown input length.
 * @param simulatePartialReads If true simulates partial reads.
 * @return The {@link FakeExtractorOutput} used in the test.
 * @throws IOException If reading from the input fails.
 * @throws InterruptedException If interrupted while reading from the input.
 */
public static FakeExtractorOutput assertOutput(Extractor extractor, String sampleFile,
    byte[] fileData, Instrumentation instrumentation, boolean simulateIOErrors,
    boolean simulateUnknownLength, boolean simulatePartialReads) throws IOException,
    InterruptedException {
  FakeExtractorInput input = new FakeExtractorInput.Builder().setData(fileData)
      .setSimulateIOErrors(simulateIOErrors)
      .setSimulateUnknownLength(simulateUnknownLength)
      .setSimulatePartialReads(simulatePartialReads).build();

  Assert.assertTrue(sniffTestData(extractor, input));
  input.resetPeekPosition();
  FakeExtractorOutput extractorOutput = consumeTestData(extractor, input, 0, true);

  if (simulateUnknownLength
      && assetExists(instrumentation, sampleFile + UNKNOWN_LENGTH_EXTENSION)) {
    extractorOutput.assertOutput(instrumentation, sampleFile + UNKNOWN_LENGTH_EXTENSION);
  } else {
    extractorOutput.assertOutput(instrumentation, sampleFile + ".0" + DUMP_EXTENSION);
  }

  SeekMap seekMap = extractorOutput.seekMap;
  if (seekMap.isSeekable()) {
    long durationUs = seekMap.getDurationUs();
    for (int j = 0; j < 4; j++) {
      long timeUs = (durationUs * j) / 3;
      long position = seekMap.getPosition(timeUs);
      input.setPosition((int) position);
      for (int i = 0; i < extractorOutput.numberOfTracks; i++) {
        extractorOutput.trackOutputs.valueAt(i).clear();
      }

      consumeTestData(extractor, input, timeUs, extractorOutput, false);
      extractorOutput.assertOutput(instrumentation, sampleFile + '.' + j + DUMP_EXTENSION);
    }
  }

  return extractorOutput;
}
 
Example 39
Project: Architecture   File: LoginTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
  App app = (App) instrumentation.getTargetContext().getApplicationContext();
  ((TestAppComponent) app.getAppComponent()).inject(this);

  when(mockedUserModel.login(eq(VALID_EMAIL), eq(VALID_PASSWORD)))
      .thenReturn(Single.just(mock(User.class)));
  when(mockedUserModel.login(eq(VALID_EMAIL), eq(INVALID_PASSWORD)))
      .thenReturn(Single.error(new AuthenticateError()));
}
 
Example 40
Project: MagicBox   File: HookHelper.java   View source code 5 votes vote down vote up
public static Instrumentation getOriginalInstrumentation(@NonNull Class<?> activityThreadClz,
                                                         @NonNull Object activityThread)
        throws ClassNotFoundException, NoSuchMethodException,
        InvocationTargetException, IllegalAccessException, NoSuchFieldException {

    Field field_instrumentation = activityThreadClz.getDeclaredField(FIELD_MINSTRUMATATION);
    field_instrumentation.setAccessible(true);
    return (Instrumentation) field_instrumentation.get(activityThread);
}