Espresso intent test failing
Instead of using IntentsTestRule
which is now @deprecated
in java, you should use the recommended activityScenarioRule
like so:
@RunWith(AndroidJUnit4::class)
@MediumTest
class YourActivityTest {
@get:Rule
val activityScenario = activityScenarioRule<YourActivity>()
@Before
fun setUp() {
launchActivity<YourActivity>()
Intents.init()
}
@After
fun tearDown() {
Intents.release()
}
@Test
fun should_goBackTo_MainActivity_onBackButton_click() {
onView(withId(R.id.goBackBtn)).perform(click())
intended(hasComponent(hasShortClassName(".MainActivity")))
}
}
Don't forget adding this in your build.gradle
file:
android {
defaultConfig {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
testOptions {
unitTests {
includeAndroidResources = true
}
}
// testing
androidTestImplementation 'androidx.test:core:1.3.1-alpha02'
androidTestImplementation 'androidx.test:core-ktx:'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
//for the activityScenarioRule syntax to work in kotlin,
//We add the ktx version of androidx.test.ext:junit
androidTestImplementation 'androidx.test.ext:junit-ktx:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.3.0'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.3.0'
androidTestImplementation 'androidx.test:runner:1.3.0'
androidTestImplementation 'androidx.test:rules:1.3.0'
}
If you are using a custom ActivityTestRule
, you can add the proper Intents.init(), Intents.release()
calls:
@Override
protected void afterActivityLaunched() {
Intents.init();
super.afterActivityLaunched();
}
@Override
protected void afterActivityFinished() {
super.afterActivityFinished();
Intents.release();
}
I had the same problem, however, switching to IntentsTestRule
did not work, too. So I switch back to ActivityTestRule
and called Intents.init()
before and Intents.release()
after the test which sent the Intent.
For more information please see this reference.
I had the same problem and solved it by using IntentsTestRule
instead of ActivityTestRule
. IntentsTestRule
is a subclass of ActivityTestRule
. Set up your @Rule
which creates the activity like so:
@Rule
public IntentsTestRule<MyActivity> mActivity = new IntentsTestRule<MyActivity>(MyActivity.class) {
@Override
protected Intent getActivityIntent() {
...
}
};
See the following project for more information: https://github.com/googlesamples/android-testing/tree/master/ui/espresso/IntentsBasicSample