android – Mock an object in Espresso-ThrowExceptions

Exception or error:

Today I started to use Espresso to test an Activity, I am practical with Junit tests but do not understand how to mock, I have the line cashPeriod that obviously gives me a NPE when I try to launch the activity with Espresso

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //no layout preview possible
    setContentView(R.layout.activity_combi_book_balance)
    title = getString(R.string.balance_details)
    setupActionBarWithHomeEnabled(true)

    val cashPeriod: CashPeriod = intent.extras.getParcelable(PERIOD_OBJECT_EXTRA)
    val sections = showList(cashPeriod)
    setAdapter(sections)
}

and my Espresso test is

@Test
    fun appLaunchesSuccessfully() {
        ActivityScenario.launch(CombiBookBalanceDetailActivity::class.java)
    }

Now if I stub the cashPeriod in the onCreate giving some hardcoded values, the test passes, but I need to do that in the test class of course

How can I mock the line val cashPeriod: CashPeriod = intent.extras.getParcelable(PERIOD_OBJECT_EXTRA) in my espresso test? Is different by Junit, where I use Mockito/mockito-kotlin/mockk and give a behaviour with when /// return //that

How to solve:

You have to use ActivityTestRule
See this

Leave a Reply

Your email address will not be published. Required fields are marked *