I'm trying to use MockContext in unit tests for Android project in android Studio. The problem is, package android.test.*
is not visible in the project.
I'm not sure what should I add to Gradle in order to import it. I tried com.android.support.test:rules:1.0.2
and androidx.test:rules:1.1.1
(one of the suggestions made by IDE), but that's not the one I'm looking for.
build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.myApp"
minSdkVersion 23
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.android.support:recyclerview-v7:28.0.0'
testImplementation 'com.android.support.test:rules:1.0.2'
}
apply plugin: 'com.google.gms.google-services'
Error message when compiling:
error: package android.test.mock does not exist
What should I add to gradle to have access to android.test
package?
Actually, you can access
android.test.mock
from your unit tests and gain access to theMockContext
class. For AndroidX projects, you can add the following in your app module'sbuild.gradle
:Source: https://developer.android.com/training/testing/set-up-project
That class is a framework class, not from a library. You can tell by the package name: anything in
android.
(instead ofcom.android.
orandroidx.
) is a framework class. Hence, you could only use that for instrumented tests, not unit tests.You can either create custom mocks (e.g., with Mockito) or use Robolectric, depending on what you're trying to do.