the following is one of my Espresso test cases.
public void testLoginAttempt() {
Espresso.onView(ViewMatchers.withId(R.id.username)).perform(View
Try with
intended(hasComponent(new ComponentName(getTargetContext(), ExpectedActivity.class)));
Look at response from @riwnodennyk
The problem is that your application performs the network operation after you click login button. Espresso doesn't handle (wait) network calls to finish by default. You have to implement your custom IdlingResource which will block the Espresso from proceeding with tests until IdlingResource returns back in Idle state, which means that network request is finished. Take a look at Espresso samples page - https://google.github.io/android-testing-support-library/samples/index.html
You can use:
intended(hasComponent(YourExpectedActivity.class.getName()));
Requires this gradle entry:
androidTestCompile ("com.android.support.test.espresso:espresso-intents:$espressoVersion")
The import for the intended()
and hasComponent()
import static android.support.test.espresso.intent.Intents.intended;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent;
as mentioned by Shubam Gupta please remember to call Intents.init()
before calling intended()
. You can eventually call it in the @Before
method.
Try:
intended(hasComponent(YourActivity.class.getName()));
Also, keep in mind
java.lang.NullPointerException
is thrown if Intents.init()
is not called before intended()
@RunWith(RobolectricTestRunner.class)
public class WelcomeActivityTest {
@Test
public void clickingLogin_shouldStartLoginActivity() {
WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class);
activity.findViewById(R.id.login).performClick();
Intent expectedIntent = new Intent(activity, LoginActivity.class);
assertThat(shadowOf(activity).getNextStartedActivity()).isEqualTo(expectedIntent);
}
}
I use this approach:
// The IntentsTestRule class initializes Espresso Intents before each test, terminates the host activity, and releases Espresso Intents after each test
@get:Rule
var tradersActivity: IntentsTestRule<TradersActivity> = IntentsTestRule(TradersActivity::class.java)
@get:Rule
var jsonViewActivity: IntentsTestRule<JsonViewActivity> = IntentsTestRule(JsonViewActivity::class.java)
@Test
fun scrollToItemAndClick() {
onView(withId(R.id.tradersRecyclerView)).perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(ITEM_POS, click()))
// check is activity was started
intended(hasComponent(JsonViewActivity::class.java.getName()))
}