I am developing an Android app using Kotlin. I am adding instrumented tests in my project. Now, I am struggling with testing if an activity is not opened after launching another activity. This is my scenario.
I have MainActivity that starts LoginActivity.
This is the code the MainActivity
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()
finish() //please, pay attention here
}, LAUNCH_DELAY)
}
protected fun startLoginActivity()
{
startActivity(Intent(this, LoginActivity::class.java))
}
}
As you can see in the code above, I am calling finish() method to kill the activity after launching LoginActivity. I want to test if the back button is pressed within login activity which is started by the main activity, the application is closed and it does not go back to the main activity.
This is my test class
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
@Rule @JvmField
val mainActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule<MainActivity>(MainActivity::class.java)
@Rule @JvmField
val loginActivityRule: ActivityTestRule<LoginActivity> = ActivityTestRule<LoginActivity>(LoginActivity::class.java)
@Before
fun setUp() {
}
@Test
fun mainActivityHistoryIsForgottenAfterStartingLoginActivity()
{
Intents.init()
Thread.sleep(MainActivity.LAUNCH_DELAY);
Intents.release()
pressBack()
//here how can I assert if the main activity is not open.
}
}
Please, pay attention to the comment in the code. I like to assert if the main activity is not opened or it does not go back to the main activity when the back button is pressed int the login activity. How can I test it?