Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActivityTestRule.getActivity returns null in Before method

I need to empty my user's data before each test

// Kotlin code
fun getActivity() = activityRule.getActivity()

Before
fun setUp() {
    cleanUp(getActivity())
}

I need to get a Context in order to do so, but in setUp, activityRule.getActivity() returns null.

I also tried:

Before
fun setUp() {
    val i = Intent()
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    activityRule.lauchActivity(i)
    cleanUp(getActivity())
}

I got an activity, but cleanUp works only half of the time (I believe some race condition apply here)

I want to avoid to cleanUp in an After function in order to see manually my app state if needed.

Is there anyway to get a context in a Before function?

Thanks

like image 425
Geob-o-matic Avatar asked May 15 '15 14:05

Geob-o-matic


Video Answer


1 Answers

You can get the production app context from InstrumentationRegistry like so: InstrumentationRegistry.getTargetContext()

Keep in mind that: InstrumentationRegistry.getContext() is the context of your test apk.

like image 89
Be_Negative Avatar answered Nov 08 '22 16:11

Be_Negative