Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android. Where did ApplicationProvider go?

I'm trying to run this line:

Context context = ApplicationProvider.getApplicationContext();

Sample code such as https://developer.android.com/training/data-storage/room/testing-db#java recommends it.

But I can't import ApplicationProvider (and I just LOVE how the documentation never imports anything, assuming your editor will prompt you correctly...). This line fails, with "error: package androidx.test.core.app does not exist":

import androidx.test.core.app.ApplicationProvider;

So where did ApplicationProvider go? I'm trying to use the current context to create a Room database:

        Context context = ApplicationProvider.getApplicationContext();
        db = Room.inMemoryDatabaseBuilder(context, TestDatabase.class).build();
        userDao = db.getUserDao();
like image 782
Phlip Avatar asked Jun 13 '19 00:06

Phlip


People also ask

What is ApplicationProvider?

public final class ApplicationProvider. Provides ability to retrieve the current application Context in tests. This can be useful if you need to access the application assets (eg getApplicationContext(). getAssets()), preferences (eg getApplicationContext().

What is AndroidX test?

AndroidX Test is a collection of Jetpack libraries that lets you run tests against Android apps. It also provides a series of tools to help you write these tests. For example, AndroidX Test provides JUnit4 rules to start activities and interact with them in JUnit4 tests.


2 Answers

Add a redundant line androidTestImplementation 'androidx.test:core:1.2.0' to build.gradle.

like image 87
Phlip Avatar answered Oct 03 '22 09:10

Phlip


add androidTestImplementation 'androidx.test:core:$version' or testImplementation 'androidx.test:core:$version' dependency based on which type of test you do to your module-level gradle file.

like image 31
reza rayatnia Avatar answered Oct 03 '22 10:10

reza rayatnia