I'm trying to use MockContext in unit tests for Android projects 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
packages?
To create a mock object for an Android dependency, add the @Mock annotation before the field declaration. To stub the behavior of the dependency, you can specify a condition and return value when the condition is met by using the when() and thenReturn() methods.
In Mockito, we mock any class using @Mock annotation. By Mocking any class, we are creating an mock object of that speicifc class. In the above code, Operators is mocked to provide dependency for Calculator class. Here, to perform test we need to annotate the function with @Test.
Actually, you can access android.test.mock
from your unit tests and gain access to the MockContext
class. For AndroidX projects, you can add the following in your app module's build.gradle
:
android {
...
useLibrary 'android.test.mock'
}
Source: https://developer.android.com/training/testing/set-up-project
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With