Search code examples
androidkotlinandroid-activityandroid-espressoinstrumented-test

Android Instrumented testing asserting if an activity is started


I am developing an Android application using Kotlin programming language. I am adding instrumentation tests into my application. Now I am trying to test if an activity is started after some delay.

This is my activity code.

class MainActivity : AppCompatActivity() {

    companion object {
        val LAUNCH_DELAY: Long = 2000
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Handler().postDelayed({
            this.startLoginActivity()
        }, LAUNCH_DELAY)
    }

    protected fun startLoginActivity()
    {
        startActivity(Intent(this, LoginActivity::class.java))
    }
}

I know how to write a simple test like this

@Test
fun itRendersCompanyName() {
    onView(withId(R.id.main_tv_company_name)).check(matches(withText("App Name")))
}

But what I am trying to test here is if the LoginActivity is launched after some delay. How can I do it using Espresso framework?


Solution

  • You can use Intents.intended() for that.

    Add following to your build.gradle file:

    androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.0'
    

    In your test function, you can try following code:

    Intents.init()
    Intents.intended(hasComponent(LoginActivity::class.java!!.getName()))
    

    You can read more about Espresso-Intents here.