5

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

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

At the moment of writing, InstrumentationRegistry is deprecated. I use ApplicationProvider.getApplicationContext<Application>() from androidx.test library instead.

The dependency is: androidTestImplementation "androidx.test.espresso:espresso-core:3.1.1"

1 Comment

androidx.test.InstrumentationRegistry is deprecated. using androidx.test.platform.app.InstrumentationRegistry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.