1

I have an Activity SomeActivity. To properly work, it needs an id. This id is passed in the Intent. SomeActivity retrieves in its onCreate-Method the id from the Intent. If it is null, it throws an Error (which crashes the Activity).

I want to test this behaviour using an Instrumented Test. My code so far :

SomeActivity.kt

class SomeActivity: AppCompatActivity() {
    private var id: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_someActivity)
        id = intent.extras?.getString("EXTRA_ID")
        if (id == null) {
            throw Error("id is null")
        }
    }
}

The Instrumented Test: SomeActivityInstrumentedTest.kt

@RunWith(AndroidJUnit4::class)
class SomeActivityInstrumentedTest{

    @get: Rule
    public var rule: ActivityScenarioRule<*> = ActivityScenarioRule(SomeActivity::class.java)

    @Test
    fun launchActivity() {
        try {
            val scenario = rule.scenario as ActivityScenario<SomeActivity>
            scenario.moveToState(Lifecycle.State.CREATED)
            scenario.moveToState(Lifecycle.State.STARTED)
            scenario.moveToState(Lifecycle.State.RESUMED)
            Assert.fail("should have failed earlier because id is not set")
        } catch (e: Error) {
            assertEquals(e.message, "id is null")
        }
    }
}

I never catch the error, the test just crashes. Is there some way to catch this error?

0 Answers0