Java 类android.app.Instrumentation 实例源码

项目:VirtualAPK    文件:LoadedPlugin.java   
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;
    }
}
项目:Demos    文件:UiTest.java   
/**
 * 测试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();
}
项目:Demos    文件:UiTest.java   
/**
 * 滑动界面,打开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();
}
项目:GitHub    文件:TiPluginTest.java   
@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();
}
项目:GitHub    文件:TiPluginTest.java   
/**
 * 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();
}
项目:DebugOverlay-Android    文件:DebugOverlayInstrumentedTest.java   
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();
    }
}
项目:android-apkbox    文件:HookActivityInstrumentationHnadler.java   
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;
    }
}
项目:pracler    文件:PlayerActivity.java   
/** 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();
    }
项目:adyen-android    文件:EspressoTestUtils.java   
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();
}
项目:adyen-android    文件:EspressoTestUtils.java   
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;
}
项目:mobile-store    文件:FileCompatTest.java   
/**
 * 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);
}
项目:civify-app    文件:CreateIssueActivityTest.java   
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()));
    }
项目:StallBuster    文件:StallBuster.java   
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();
    }
}
项目:ExoPlayer-Offline    文件:FakeExtractorOutput.java   
/**
 * 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);
  }
}
项目:RNLearn_Project1    文件:ReactIdleDetectionUtil.java   
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!");
}
项目:Sherlock    文件:CrashListActivityTest.java   
@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)));
}
项目:MagicBox    文件:Secy.java   
@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);
        }
    }
项目:VirtualAPK    文件:VAInstrumentation.java   
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;
}
项目:VirtualAPK    文件:PluginManager.java   
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();
    }
}
项目:mvp-core    文件:ActivityLifecycleTestRule.java   
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);
    }
}
项目:webtrekk-android-sdk    文件:WebtrekkBaseSDKTest.java   
@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);
    }
}
项目:androidnative.pri    文件:ExampleActivityTest.java   
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);
}
项目:dagger-test-example    文件:WeatherFragmentTest.java   
@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());
}
项目:firefox-tv    文件:ScreenshotTest.java   
@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();
}
项目:DroidPlugin    文件:InstrumentationHook.java   
@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");
    }
}
项目:cat-is-a-dog    文件:AddHabitEventActivityTest.java   
@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()));
}
项目:TPlayer    文件:HookHelper.java   
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);
}
项目:AndroidTestingTutorial    文件:GalleryPickerTesting.java   
@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();
    }
}
项目:GitHub    文件:DbTest.java   
/** 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;
}
项目:DebugOverlay-Android    文件:DebugOverlayInstrumentedTest.java   
@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);
    }
}
项目:adyen-android    文件:EspressoTestUtils.java   
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);
    }
}
项目:mobile-store    文件:FileCompatTest.java   
@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());
}
项目:RNLearn_Project1    文件:ReactTestHelper.java   
public static ReactTestFactory getReactTestFactory() {
  Instrumentation inst = InstrumentationRegistry.getInstrumentation();
  if (!(inst instanceof ReactTestFactory)) {
    return new DefaultReactTestFactory();
  }

  return (ReactTestFactory) inst;
}
项目:Dominate    文件:PpwButtonService.java   
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();
}
项目:Dominate    文件:PpwButtonService.java   
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();
}
项目:ExoPlayer-Offline    文件:TestUtil.java   
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);
}
项目:RNLearn_Project1    文件:ReactTestHelper.java   
public static ReactTestFactory getReactTestFactory() {
  Instrumentation inst = InstrumentationRegistry.getInstrumentation();
  if (!(inst instanceof ReactTestFactory)) {
    return new DefaultReactTestFactory();
  }

  return (ReactTestFactory) inst;
}
项目:ExoPlayer-Offline    文件:TestUtil.java   
/**
 * 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;
}
项目:Architecture    文件:LoginTest.java   
@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()));
}
项目:MagicBox    文件:HookHelper.java   
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);
}