Java Code Examples for android.app.Instrumentation#runOnMainSync()

The following examples show how to use android.app.Instrumentation#runOnMainSync() . 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: UnifiedFragmentHelperTest.java    From OPFIab with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("PMD.UnusedPrivateMethod")
private static FragmentIabHelper getHelper(final boolean isSupport, final Object fragment,
                                           final OnPurchaseListener listener,
                                           Instrumentation instrumentation)
        throws InterruptedException {
    final FragmentIabHelper[] helpers = new FragmentIabHelper[1];
    instrumentation.runOnMainSync(new Runnable() {
        @Override
        public void run() {
            if (isSupport) {
                helpers[0] = ((SupportTestFragment) fragment).getIabHelper(listener);
            } else {
                helpers[0] = ((TestFragment) fragment).getIabHelper(listener);
            }
        }
    });
    Thread.sleep(WAIT_INIT);
    return helpers[0];
}
 
Example 2
Source File: LPWebInterstitialMessageSnapshotTest.java    From Leanplum-Android-SDK with Apache License 2.0 6 votes vote down vote up
@Test
public void testWebInterstitial() throws InterruptedException {
  Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
  Leanplum.setApplicationContext(getMainActivity());

  instrumentation.runOnMainSync(new Runnable() {
    @Override
    public void run() {
      messageView = createMessageView();
      setupView(messageView);
    }
  });

  Thread.sleep(7000); // wait until WebView is rendered

  instrumentation.runOnMainSync(new Runnable() {
    @Override
    public void run() {
      snapshotView(messageView);
    }
  });
}
 
Example 3
Source File: LPRichInterstitialMessageSnapshotTest.java    From Leanplum-Android-SDK with Apache License 2.0 6 votes vote down vote up
@Test
public void testRichInterstitial() throws InterruptedException {
  Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
  Leanplum.setApplicationContext(getMainActivity());

  instrumentation.runOnMainSync(new Runnable() {
    @Override
    public void run() {
      messageView = createMessageView();
      setupView(messageView);
    }
  });

  Thread.sleep(7000); // wait until WebView is rendered

  instrumentation.runOnMainSync(new Runnable() {
    @Override
    public void run() {
      snapshotView(messageView);
    }
  });
}
 
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: ListActivityTest.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 6
Source File: CoordinatesUtil.java    From android-test with Apache License 2.0 6 votes vote down vote up
static int[] getCoordinatesInMiddleOfSendButton(
    Activity activity, Instrumentation instrumentation) {
  final View sendButton = activity.findViewById(R.id.send_button);
  final int[] xy = new int[2];
  instrumentation.runOnMainSync(
      new Runnable() {
        @Override
        public void run() {
          sendButton.getLocationOnScreen(xy);
        }
      });
  int x = xy[0] + (sendButton.getWidth() / 2);
  int y = xy[1] + (sendButton.getHeight() / 2);
  int[] xyMiddle = {x, y};
  return xyMiddle;
}
 
Example 7
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 8
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 9
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 10
Source File: ComponentActivityTestRule.java    From litho with Apache License 2.0 5 votes vote down vote up
/** Set ComponentTree for the Activity to display. */
public void setComponentTree(final ComponentTree componentTree) {
  final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
  instrumentation.runOnMainSync(
      new Runnable() {
        @Override
        public void run() {
          getActivity().setComponentTree(componentTree);
        }
      });
  instrumentation.waitForIdleSync();
}
 
Example 11
Source File: UnifiedFragmentHelperTest.java    From OPFIab with Apache License 2.0 5 votes vote down vote up
private static Object createFragment(boolean isSupport, Activity activity,
                                     Instrumentation instrumentation, int color)
        throws InterruptedException {
    final Object fragment;
    if (isSupport) {
        fragment = SupportTestFragment.getInstance(color);
        final android.support.v4.app.FragmentManager supportFragmentManager = ((FragmentActivity) activity).getSupportFragmentManager();
        supportFragmentManager
                .beginTransaction()
                .replace(R.id.content, (android.support.v4.app.Fragment) fragment, FRAGMENT_TAG)
                .commit();
        instrumentation.runOnMainSync(new Runnable() {
            @Override
            public void run() {
                supportFragmentManager.executePendingTransactions();
            }
        });
    } else {
        fragment = TestFragment.getInstance(color);
        final FragmentManager fragmentManager = activity.getFragmentManager();
        fragmentManager
                .beginTransaction()
                .replace(R.id.content, (Fragment) fragment, FRAGMENT_TAG)
                .commit();
        instrumentation.runOnMainSync(new Runnable() {
            @Override
            public void run() {
                fragmentManager.executePendingTransactions();
            }
        });
    }
    Thread.sleep(WAIT_INIT);
    return fragment;
}
 
Example 12
Source File: Intents.java    From android-test with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that the given matcher matches a specified number of intents sent by the application
 * under test. This is an equivalent of verify(mock, times(num)) in Mockito. Verification does not
 * have to occur in the same order as the intents were sent. Intents are recorded from the time
 * that Intents.init is called.
 *
 * @param matcher the {@link Matcher} to be applied to captured intents
 * @throws AssertionFailedError if the given {@link Matcher} did not match the expected number of
 *     recorded intents
 */
public static void intended(
    final Matcher<Intent> matcher, final VerificationMode verificationMode) {
  checkNotNull(defaultInstance, "Intents not initialized. Did you forget to call init()?");
  Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
  instrumentation.waitForIdleSync();
  if (resumedActivitiesExist(instrumentation)) {
    // Running through Espresso to take advantage of its synchronization mechanism.
    onView(isRoot())
        .check(
            new ViewAssertion() {
              @Override
              public void check(View view, NoMatchingViewException noViewFoundException) {
                defaultInstance.internalIntended(matcher, verificationMode, recordedIntents);
              }
            });
  } else {
    // No activities are resumed, so we don't need Espresso's synchronization.
    PropogatingRunnable intendedRunnable =
        new PropogatingRunnable(
            new Runnable() {
              @Override
              public void run() {
                defaultInstance.internalIntended(matcher, verificationMode, recordedIntents);
              }
            });
    instrumentation.runOnMainSync(intendedRunnable);
    instrumentation.waitForIdleSync();
    intendedRunnable.checkException();
  }
}
 
Example 13
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 14
Source File: LoginInstrumentedTest.java    From flowless with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    Espresso.registerIdlingResources(EspressoIdlingResource.getIdlingResource());
    mainActivityActivityTestRule.launchActivity(null);
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    MainActivity mainActivity = mainActivityActivityTestRule.getActivity();
    instrumentation.runOnMainSync(() -> {
        Flow.get(mainActivity.getBaseContext()).setHistory(History.single(LoginKey.create()), Direction.REPLACE);
    });
    ServiceProvider serviceProvider = ServiceProvider.get(mainActivity.getBaseContext());
    LoginComponent loginComponent = serviceProvider.getService(LoginKey.create(), DaggerService.TAG);
    loginPresenter = loginComponent.loginPresenter();
}
 
Example 15
Source File: ComponentActivityTestRule.java    From litho with Apache License 2.0 5 votes vote down vote up
/** Set the Component for the Activity to display. */
public void setComponent(final Component component) {
  final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
  instrumentation.runOnMainSync(
      new Runnable() {
        @Override
        public void run() {
          getActivity().setComponent(component);
        }
      });
  instrumentation.waitForIdleSync();
}
 
Example 16
Source File: UnifiedFragmentHelperTest.java    From OPFIab with Apache License 2.0 4 votes vote down vote up
public static void registerUnregisterHomeButton(Instrumentation instrumentation,
                                                final Activity activity, UiDevice uiDevice)
        throws InterruptedException {

    final String providerName = String.format(TEST_PROVIDER_NAME_FMT, "HOME");
    final BillingProvider billingProvider = new MockBillingProviderBuilder()
            .setWillPostSuccess(true)
            .setName(providerName)
            .setIsAvailable(true)
            .setSleepTime(WAIT_BILLING_PROVIDER)
            .build();

    final TestManager testPurchaseManager = new TestManager.Builder()
            .expectEvent(new PurchaseResponseValidator(providerName, true))
            .expectEvent(new PurchaseResponseValidator(providerName, true))
            .expectEvent(new AlwaysFailValidator())
            .setTag("Purchase")
            .setSkipWrongEvents(false)
            .build();
    final BillingManagerAdapter purchaseListenerAdapter = new BillingManagerAdapter(
            testPurchaseManager);

    final TestManager testGlobalListenerManager = new TestManager.Builder()
            .expectEvent(new SetupStartedEventValidator())
            .expectEvent(new SetupResponseValidator(providerName))
            .expectEvent(new PurchaseRequestValidator(SKU_CONSUMABLE))
            .expectEvent(new PurchaseResponseValidator(providerName, true))
            .expectEvent(new PurchaseRequestValidator(SKU_CONSUMABLE))
            .expectEvent(new PurchaseResponseValidator(providerName, true))
            .expectEvent(new PurchaseRequestValidator(SKU_CONSUMABLE))
            .expectEvent(new PurchaseResponseValidator(providerName, true))
            .setStrategy(TestManager.Strategy.UNORDERED_EVENTS)
            .setTag("Global")
            .build();

    final TestManager[] managers = {testGlobalListenerManager, testPurchaseManager};

    final Configuration configuration = new Configuration.Builder()
            .addBillingProvider(billingProvider)
            .setBillingListener(new BillingManagerAdapter(testGlobalListenerManager))
            .build();

    instrumentation.runOnMainSync(new Runnable() {
        @Override
        public void run() {
            OPFIab.init(activity.getApplication(), configuration);
        }
    });
    Thread.sleep(WAIT_INIT);
    final boolean isSupport = activity instanceof FragmentActivity;
    Object fragment = createFragment(isSupport, activity, instrumentation, R.color.blue);

    FragmentIabHelper helper = getHelper(isSupport, fragment, purchaseListenerAdapter,
            instrumentation);

    purchase(instrumentation, helper, SKU_CONSUMABLE);

    changeToHomeScreen(uiDevice);

    purchase(instrumentation, helper, SKU_CONSUMABLE);

    reopenActivity(instrumentation);

    fragment = getFragment(isSupport);
    helper = getHelper(isSupport, fragment, purchaseListenerAdapter, instrumentation);

    pressBackButton(uiDevice);

    purchase(instrumentation, helper, SKU_CONSUMABLE);

    purchaseListenerAdapter.validateEvent(AlwaysFailValidator.getStopObject());

    for (TestManager manager : managers) {
        Assert.assertTrue(manager.await(WAIT_TEST_MANAGER));
    }
}
 
Example 17
Source File: UnifiedFragmentHelperTest.java    From OPFIab with Apache License 2.0 4 votes vote down vote up
private static void purchase(Instrumentation instrumentation, IabHelper helper, String sku,
                             long timeout)
        throws InterruptedException {
    instrumentation.runOnMainSync(new PurchaseRunnable(helper, sku));
    Thread.sleep(timeout);
}
 
Example 18
Source File: UnifiedFragmentHelperTest.java    From OPFIab with Apache License 2.0 4 votes vote down vote up
public static void registerUnregisterFragmentReplace(Instrumentation instrumentation,
                                                     final Boolean isSupport,
                                                     UiDevice uiDevice)
        throws InterruptedException {
    final String providerName = String.format(TEST_PROVIDER_NAME_FMT, "FRAGMENT_REPLACE");
    final Activity activity;
    if (isSupport) {
        activity = EmptyFragmentActivity.getLastInstance();
    } else {
        activity = EmptyActivity.getLastInstance();
    }

    final BillingProvider billingProvider = new MockBillingProviderBuilder()
            .setWillPostSuccess(true)
            .setName(providerName)
            .setIsAvailable(true)
            .setSleepTime(WAIT_BILLING_PROVIDER)
            .build();

    final TestManager testPurchaseManager = new TestManager.Builder()
            .expectEvent(new PurchaseResponseValidator(providerName, true))
            .expectEvent(new AlwaysFailValidator())
            .expectEvent(new PurchaseResponseValidator(providerName, true))
            .setTag("Purchase")
            .build();
    final BillingManagerAdapter purchaseListenerAdapter = new BillingManagerAdapter(
            testPurchaseManager);

    final TestManager testGlobalListenerManager = new TestManager.Builder()
            .expectEvent(new SetupStartedEventValidator())
            .expectEvent(new SetupResponseValidator(providerName))
            .expectEvent(new PurchaseRequestValidator(SKU_CONSUMABLE))
            .expectEvent(new PurchaseResponseValidator(providerName, true))
            .expectEvent(new PurchaseRequestValidator(SKU_CONSUMABLE))
            .expectEvent(new PurchaseResponseValidator(providerName, true))
            .expectEvent(new PurchaseRequestValidator(SKU_CONSUMABLE))
            .expectEvent(new PurchaseResponseValidator(providerName, true))
            .setStrategy(TestManager.Strategy.UNORDERED_EVENTS)
            .setTag("Global")
            .build();

    final Configuration configuration = new Configuration.Builder()
            .addBillingProvider(billingProvider)
            .setBillingListener(new BillingManagerAdapter(testGlobalListenerManager))
            .build();

    final TestManager[] managers = {testGlobalListenerManager, testPurchaseManager};

    final FragmentIabHelper[] helpers = new FragmentIabHelper[1];
    instrumentation.runOnMainSync(new Runnable() {
        @Override
        public void run() {
            OPFIab.init(activity.getApplication(), configuration);
        }
    });
    Thread.sleep(WAIT_INIT);
    final Object fragment = createFragment(isSupport, activity, instrumentation, R.color.green);
    final FragmentIabHelper helper = getHelper(isSupport, fragment, purchaseListenerAdapter,
            instrumentation);

    purchase(instrumentation, helper, SKU_CONSUMABLE);
    Thread.sleep(WAIT_PURCHASE);

    replaceFragment(activity);

    purchase(instrumentation, helper, SKU_CONSUMABLE);
    Thread.sleep(WAIT_LAUNCH_SCREEN);

    restoreFragment(activity);

    purchaseListenerAdapter.validateEvent(AlwaysFailValidator.getStopObject());

    purchase(instrumentation, helper, SKU_CONSUMABLE);
    Thread.sleep(WAIT_PURCHASE);

    for (TestManager manager : managers) {
        Assert.assertTrue(manager.await(WAIT_TEST_MANAGER));
    }
}