Search code examples
androidandroid-testingandroidx

What do I need to import to use launchActivity<>() in UnitTests?


So I'm trying to test my activity following googles instructions here: https://developer.android.com/guide/components/activities/testing

But the code launchActivity<MyActivity>() does not work. Do I need to define launchActivity as a rule or is there a library I need to import in gradle?

These are the imports I already have

testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'

Solution

  • Do I need to define launchActivity as a rule or is there a library I need to import in gradle?

    Yes. You'll need to set up a rule at the beginning of your test class like this;

    @RunWith(AndroidJUnit4.class)
    public class YourActivityTests extends AndroidJUnitRunner {
    
        @Rule
        public ActivityTestRule<YourActivity> mYourActivityActivityTestRule =
            new ActivityTestRule<YourActivity>(YourActivity.class);
    

    The required library imports are bundled in import androidx.test package.

    This is for Java, but, there should be an equivalent way in Kotlin. Hope this helps.

    Edit: You should use the latest stable builds (the ones with only numbers in versioning) for production apps. Only use any -alpha or -rc suffixed versions when you really need those versions of the library.