I am trying to write the following unit test for a function in my project
import android.content.Context
import org.junit.Test
import androidx.test.core.app.ApplicationProvider
import com.adi_random.tracky.api.searchBook
import com.adi_random.tracky.models.GoodreadsBook
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException
import com.google.common.truth.Truth.assertThat
/**
* Created by meadi on 6/27/2020.
*/
class BookFetchTest {
/**
* Test if the Tracy API searchBook endpoint returns the expected result and gets parsed correctly
*/
val context = ApplicationProvider.getApplicationContext<Context>()
#Test
fun bookFetchResultValidation() {
val query = "Dune";
searchBook(query, context, object : Callback {
override fun onFailure(call: Call, e: IOException) {
TODO("Not yet implemented")
}
override fun onResponse(call: Call, response: Response) {
val gson = Gson();
val res = gson.fromJson<Array<GoodreadsBook>>(
response.body?.charStream(),
Array<GoodreadsBook>
::class.java
)
assertThat(res).hasLength(20);
}
})
}
}
When hitting run, I am getting Unresolved reference in :app:compileDebugUnitTestKotlin gradle task for the following dependencies: test (double clicking the error highlights androidx.test.core.app.ApplicationProvider), common ( in com.google.common.truth.Truth.assertThat), ApplicationProvider ( in ApplicationProvider.getApplicationContext()) and assertThat (in the assertThat call at the end of the test).
Here is my module build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
buildFeatures {
viewBinding true
}
testOptions {
unitTests.includeAndroidResources = true
}
defaultConfig {
applicationId "com.adi_random.tracky"
minSdkVersion 23
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
useLibrary 'android.test.runner'
useLibrary 'android.test.base'
useLibrary 'android.test.mock'
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.squareup.okhttp3:okhttp:4.1.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.navigation:navigation-fragment-ktx:2.1.0'
implementation 'androidx.navigation:navigation-ui-ktx:2.1.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.ext:truth:1.2.0'
androidTestImplementation 'com.google.truth:truth:0.42'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test:core:1.2.0'
// AndroidJUnitRunner and JUnit Rules
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
}
As you can see I have those dependencies added to my gradle build file with the androidTestImplementation directive, so I don't understand why those errors get thrown. Does anyone have any idea? Thanks in advance!
Edit:Here is a screenshot of the problem:
Add this dependency:
def androidx_test_core = "1.2.0"
androidTestImplementation "androidx.test:core-ktx:$androidx_test_core"
def androidx_test_ext = "1.1.1"
androidTestImplementation "androidx.test.ext:junit-ktx:$androidx_test_ext"
def hamcrestVersion = '2.2'
testImplementation "org.hamcrest:hamcrest:$hamcrestVersion"
Related
Learning Unit testing on android, my tests are not running now, says "Test events were not received, not much details on the stack trace I tried adding and removing some dependencies but did not worked. looked into some other stackoverflow results still not working, I am doing this by following a udemy course on TDD.
Here is one of my test classes
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import petros.efthymiou.groovy.utils.BaseUnitTest
import petros.efthymiou.groovy.utils.getValueForTest
class PlayListViewModelShould:BaseUnitTest() {
private val repository: PlayListRepository = mock()
private val playList = mock<List<PlayList>>()
private val expected = Result.success(playList)
private val exception = java.lang.RuntimeException("SOMETHING NOT RIGHT")
#OptIn(ExperimentalCoroutinesApi::class)
#Test
suspend fun getPlaylistsFromRepository()= runTest{
val viewModel = mockSuccesfulCase()
viewModel.playlists.getValueForTest()
verify(repository,times(1)).getPlaylists()
}
#OptIn(ExperimentalCoroutinesApi::class)
#Test
fun emitPlaylistsFromRepository()= runTest {
val viewModel = mockSuccesfulCase()
assertEquals(expected, viewModel.playlists.getValueForTest())
}
#OptIn(ExperimentalCoroutinesApi::class)
#Test
fun emitErrorWhenRecieveError() {
runTest {
whenever(repository.getPlaylists()).thenReturn(
flow {
emit(Result.failure<List<PlayList>>(exception))
}
)
}
val viewModel = PlayListViewModel(repository)
assertEquals(java.lang.RuntimeException("another error"), viewModel.playlists.getValueForTest()!!.exceptionOrNull())
}
private fun mockSuccesfulCase(): PlayListViewModel {
runBlocking {
whenever(repository.getPlaylists()).thenReturn(
flow {
emit(expected)
}
)
}
return PlayListViewModel(repository)
}
}
My gradle
android {
compileSdkVersion 30
defaultConfig {
applicationId "petros.efthymiou.groovy"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
testOptions {
execution 'ANDROIDX_TEST_ORCHESTRATOR'
unitTests.all {
useJUnitPlatform()
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
freeCompilerArgs = freeCompilerArgs + "-Xallow-result-return-type"
}
testOptions {
animationsDisabled = true
}
buildFeatures {
viewBinding true
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.0-alpha04'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'com.jakewharton.espresso:okhttp3-idling-resource:1.0.0'
// testImplementation 'com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0'
testImplementation 'org.mockito:mockito-inline:2.21.0'
testImplementation 'androidx.arch.core:core-testing:2.1.0'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.8'
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.1")
testImplementation 'org.mockito.kotlin:mockito-kotlin:4.0.0'
testImplementation "org.mockito:mockito-core:4.3.1"
androidTestImplementation "org.mockito:mockito-android:3.10.0"
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.9.1'
testImplementation 'org.junit.vintage:junit-vintage-engine:5.9.1'
androidTestImplementation 'com.jakewharton.espresso:okhttp3-idling-resource:1.0.0'
androidTestImplementation 'androidx.test:runner:1.5.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
androidTestImplementation "org.mockito:mockito-core:4.3.1"
androidTestImplementation 'junit:junit:4.13.2'
androidTestImplementation "org.robolectric:robolectric:4.3.1"
androidTestImplementation('com.schibsted.spain:barista:3.6.0') {
exclude group: 'org.jetbrains.kotlin' // Only if you already use Kotlin in your project
}
}
I'm writing a jetpack compose android app, I need to store some settings permanently.
I decided to use androidx.datastore:datastore-preferences:1.0.0 library, I have added this to my classpath.
According to the https://developer.android.com/topic/libraries/architecture/datastore descripton I have added this line of code to my kotlin file at the top level:
val Context.prefsDataStore: DataStore by preferencesDataStore(name = "settings")
But I get a compile error:
e: ...SettingsViewModel.kt: (13, 50): Property delegate must have a 'getValue(Context, KProperty<*>)' method. None of the following functions is suitable:
public abstract operator fun getValue(thisRef: Context, property: KProperty<*>): DataStore<Preferences> defined in kotlin.properties.ReadOnlyProperty
How can I use the datastore-preferences?
My build.gradle file:
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
}
apply plugin: 'dagger.hilt.android.plugin'
apply plugin: 'kotlinx-serialization'
android {
compileSdk 31
defaultConfig {
applicationId "hu.homedashboard.mobile"
minSdk 22
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
useIR = true
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion compose_version
kotlinCompilerVersion "$kotlinVersion"
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}
dependencies {
implementation "androidx.activity:activity-compose:1.3.1"
implementation "androidx.appcompat:appcompat:1.3.1"
implementation "androidx.datastore:datastore-preferences:1.0.0"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation "androidx.compose.ui:ui:$compose_version"
implementation "com.google.accompanist:accompanist-swiperefresh:0.20.3"
implementation "androidx.core:core-ktx:1.6.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.1"
implementation "androidx.lifecycle:lifecycle-viewmodel-compose:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.navigation:navigation-compose:2.4.0-alpha10"
implementation "com.google.android.material:material:1.4.0"
implementation "com.google.dagger:hilt-android:2.40.1"
implementation "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0"
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0"
implementation "org.ocpsoft.prettytime:prettytime:5.0.2.Final"
implementation 'androidx.hilt:hilt-navigation-compose:1.0.0-alpha03'
kapt "com.google.dagger:hilt-compiler:2.38.1"
kapt "com.google.dagger:dagger-android-processor:2.40.1"
kapt "com.google.guava:guava:31.0.1-android"
api "com.google.guava:guava:31.0.1-android"
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
}
kapt {
correctErrorTypes true
javacOptions {
option("-Xmaxerrs", 500)
}
}
I got this error because of an incorrect import:
import java.util.prefs.Preferences
So fix it by
import androidx.datastore.preferences.core.Preferences
or
val Context.dataStore by preferencesDataStore(name = "settings")
I am trying to build a Kotlin manga application through Android Studio, but I get an error like
I tried googling, but I could not find anything other than an article on SOF, if I understood correctly, this does not work for me
build.gradle(:app)
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
id 'kotlin-parcelize'
}
android {
compileSdkVersion 31
buildToolsVersion '30.0.3'
defaultConfig {
applicationId 'org.nkno.yumu'
minSdkVersion 21
targetSdkVersion 31
versionCode 374
versionName 'beta1'
generatedDensities = []
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
kapt {
arguments {
arg 'room.schemaLocation', "$projectDir/schemas".toString()
}
generateStubs = true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
debug {
applicationIdSuffix = '.debug'
}
release {
multiDexEnabled false
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
buildFeatures {
viewBinding true
}
sourceSets {
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
}
lintOptions {
disable 'MissingTranslation'
abortOnError false
}
testOptions {
unitTests.includeAndroidResources = true
unitTests.returnDefaultValues = false
}
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = JavaVersion.VERSION_1_8.toString()
freeCompilerArgs += [
'-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi',
]
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2'
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.activity:activity-ktx:1.4.0'
implementation 'androidx.fragment:fragment-ktx:1.4.0'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
implementation 'androidx.lifecycle:lifecycle-service:2.4.0'
implementation 'androidx.lifecycle:lifecycle-process:2.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'androidx.viewpager2:viewpager2:1.1.0-beta01'
implementation 'androidx.preference:preference-ktx:1.1.1'
implementation 'androidx.work:work-runtime-ktx:2.7.1'
implementation 'com.google.android.material:material:1.4.0'
//noinspection LifecycleAnnotationProcessorWithJava8
kapt 'androidx.lifecycle:lifecycle-compiler:2.4.0'
implementation 'androidx.room:room-runtime:2.3.0'
implementation 'androidx.room:room-ktx:2.3.0'
kapt 'androidx.room:room-compiler:2.3.0'
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
implementation 'com.squareup.okio:okio:2.10.0'
implementation 'org.jsoup:jsoup:1.14.3'
implementation 'com.hannesdorfmann:adapterdelegates4-kotlin-dsl:4.3.1'
implementation 'com.hannesdorfmann:adapterdelegates4-kotlin-dsl-viewbinding:4.3.1'
implementation 'io.insert-koin:koin-android:3.1.4'
implementation 'io.coil-kt:coil-base:1.4.0'
implementation 'com.davemorrissey.labs:subsampling-scale-image-view-androidx:3.10.0'
implementation 'com.github.solkin:disk-lru-cache:1.3'
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.7'
testImplementation 'junit:junit:4.13.2'
testImplementation 'com.google.truth:truth:1.1.3'
testImplementation 'org.json:json:20210307'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.5.2'
testImplementation 'io.insert-koin:koin-test-junit4:3.1.4'
androidTestImplementation 'androidx.test:runner:1.4.0'
androidTestImplementation 'androidx.test:rules:1.4.0'
androidTestImplementation 'androidx.test:core-ktx:1.4.0'
androidTestImplementation 'androidx.test.ext:junit-ktx:1.1.3'
androidTestImplementation 'androidx.room:room-testing:2.3.0'
androidTestImplementation 'com.google.truth:truth:1.1.3'
}
Sorry for the wrong formatting)
Full error message:
e: C:\Users\USER\Desktop\Yumu-manga\app\build\tmp\kapt3\stubs\debug\error\NonExistentClass.java:3: error: Dao class must be annotated with #Dao
public final class NonExistentClass {
^
So far I'm new to Kotlin, but I'm pretty good at Java.
I use Room in this project.
app\build\tmp\kapt3\stubs\debug\error\NonExistentClass.java
package error;
public final class NonExistentClass {
}
error message 2
error: Dao class must be an abstract class or an interface
I am trying to run the following Espresso test. I have Android Hilt dependency injection setup in my project and its working well in the application but am facing issues running UI tests.
I also have a project library which is using Hilt aswell.
Getting the following Exception:
Process: com.muddassir.myapp, PID: 15570
java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/test/internal/platform/tracker/UsageTracker;
at java.lang.Class.newInstance(Native Method)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6952)
at android.app.ActivityThread.access$1500(ActivityThread.java:272)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2055)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8019)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.test.internal.platform.tracker.UsageTracker" on path: DexPathList[[zip file "/system/framework/android.test.runner.jar", zip file "/system/framework/android.test.mock.jar", zip file "/data/app/com.muddassir.myapp.test-sXVdfWq9tpbgNg9sbalPuAase.apk", zip file "/data/app/com.cs.stackoverflow-hHsBjEoBRyEmFRYwawGgqA==/base.apk"],nativeLibraryDirectories=[/data/app/com.cs.stackoverflow.test-sXVdfWq9tpbgNg9sbalPuA==/lib/arm, /data/app/com.cs.stackoverflow-hHsBjEoBRyEmFRYwawGgqA==/lib/arm, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
My test is as follows
package com.muddassir.myapp.ui.activity
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import com.cs.stackoverflow.R
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.internal.runners.JUnit4ClassRunner
import org.junit.runner.RunWith
#LargeTest
#HiltAndroidTest
#RunWith(AndroidJUnit4ClassRunner::class)
class ParameterTest {
#get:Rule()
var hiltRule = HiltAndroidRule(this)
#get:Rule
val activityRule = AndroidJUnit4ClassRunner(MainActivity::class.java)
#Before
fun init() {
hiltRule.inject()
}
#Test
fun parameterTest() {
val recyclerView = onView(
allOf(
withId(R.id.questionsRv),
childAtPosition(
withId(R.id.swipeToRefreshL),
0
)
)
)
recyclerView.perform(actionOnItemAtPosition<ViewHolder>(0, click()))
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int
): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
lib/build.gradle
plugins {
id 'com.android.library'
id 'kotlin-android'
id 'kotlin-android-extensions'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "com.cs.myapp_lib.HiltTestRunner"
consumerProguardFiles "consumer-rules.pro"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
def test_version = "1.3.1-alpha03"
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
// Retrofit
def retrofit = "2.9.0"
api "com.squareup.retrofit2:retrofit:$retrofit"
api "com.squareup.retrofit2:converter-gson:$retrofit"
api "com.squareup.retrofit2:converter-scalars:$retrofit"
api "com.squareup.retrofit2:adapter-rxjava2:$retrofit"
api 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2'
// Utilities
api 'com.github.muddassir235:kmacros:1.10'
def room = "2.2.6"
api "androidx.room:room-runtime:$room"
api "androidx.room:room-ktx:$room"
kapt "androidx.room:room-compiler:$room"
// Dependency Injection through HILT
def hilt_version = '2.31.2-alpha'
api "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
// ...with Kotlin.
kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"
def hilt_view_models = '1.0.0-alpha03'
api "androidx.hilt:hilt-lifecycle-viewmodel:$hilt_view_models"
kapt "androidx.hilt:hilt-compiler:$hilt_view_models"
// Libraries for tests
kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"
testImplementation 'junit:junit:4.13.1'
androidTestImplementation 'androidx.test.ext:junit:1.3.1-alpha03'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0-alpha03'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.4.0-alpha03'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.4.0-alpha03'
androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.4.0-alpha03'
androidTestImplementation 'androidx.test.espresso:espresso-web:3.4.0-alpha03'
androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.4.0-alpha03'
androidTestImplementation 'androidx.test:runner:1.3.1-alpha03'
androidTestImplementation "androidx.test:core-ktx:$test_version"
androidTestImplementation 'androidx.test:rules:1.3.1-alpha03'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.4.0-alpha03'
androidTestImplementation "com.google.dagger:hilt-android-testing:$hilt_version"
}
app/build.gradle
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-android-extensions'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
id 'androidx.navigation.safeargs.kotlin'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.cs.stackoverflow"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "com.muddassir.myapp.HiltTestRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation project(':stackoverflow_lib')
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
// Dependency Injection through HILT
def hilt_version = '2.31.2-alpha'
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
// ...with Kotlin.
kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"
// ...with Java.
// androidTestAnnotationProcessor 'com.google.dagger:hilt-android-compiler:2.28-alpha'
def hilt_view_models = '1.0.0-alpha03'
implementation "androidx.hilt:hilt-lifecycle-viewmodel:$hilt_view_models"
kapt "androidx.hilt:hilt-compiler:$hilt_view_models"
// Libraries for tests
kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"
def fragment_version = '1.3.0-rc02'
debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
def test_version = "1.3.1-alpha03"
def nav_version = '2.3.3'
// Kotlin
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"
testImplementation 'junit:junit:4.13.1'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0-alpha03'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.4.0-alpha03'
androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.4.0-alpha03'
androidTestImplementation 'androidx.test.espresso:espresso-web:3.4.0-alpha03'
androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.4.0-alpha03'
androidTestImplementation 'androidx.test:runner:1.3.1-alpha03'
androidTestImplementation 'androidx.test:rules:1.3.1-alpha03'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.4.0-alpha03'
androidTestImplementation "com.google.dagger:hilt-android-testing:$hilt_version"
androidTestImplementation "androidx.test:core-ktx:$test_version"
androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"
}
Project build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.4.30"
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.2"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.3"
}
}
allprojects {
repositories {
google()
jcenter()
maven { url "https://jitpack.io" }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Use the stable versions of the test runner and rules 1.3.0 or 1.3.1-alpha02
implementation "androidx.test:runner:1.3.0"
implementation "androidx.test:rules:1.3.0"
I'm facing the same.
If we use hilt test with custom runner class then we got issues in runner class.
testInstrumentationRunner "com.example.testing.HiltTestRunner"
so while using hilt, the manual test cases would be better.
I have watched and read many tutorial on How to use Room persistence library with coroutines but whenever I use coroutine in my file it forces me to annotate my code with #InternalCoroutineApi but in the tutorial they don't need to annotate anything.
Now I'm wanted to know
1. What does this annotation means?
2. Why it is necessary?
3. How can I avoid this?
Even this answer doesn't help me either.
below is the how I created my data base and my build.gradle file
import android.content.Context
import androidx.room.Database
import androidx.room.Entity
import androidx.room.Room
import androidx.room.RoomDatabase
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.internal.synchronized
#Database(entities = [Post::class], version = 1, exportSchema = false)
public abstract class PostRoomDatabase: RoomDatabase() {
abstract fun getDao(): PostDao
companion object{
//Companion object provide the same functionality as the Static keyword in java
#Volatile
private var DATABASE_INSTANCE :PostRoomDatabase? = null
#InternalCoroutinesApi
fun getDatabase(context: Context) : PostRoomDatabase{
val tempInstance = DATABASE_INSTANCE
if(tempInstance != null){
return tempInstance
}
synchronized(this){
val instance = Room.databaseBuilder(
context.applicationContext,
PostRoomDatabase::class.java,
"post_database"
).build()
DATABASE_INSTANCE = instance;
return instance
}
}
}
}
Build.gradle file
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 28
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "vijay.bhadolia.seed"
minSdkVersion 23
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
// To inline the bytecode built with JVM target 1.8 into
// bytecode that is being built with JVM target 1.6. (e.g. navArgs)
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
def room_version = "2.2.5"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.navigation:navigation-fragment:2.2.2'
implementation 'androidx.navigation:navigation-ui:2.2.2'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.navigation:navigation-fragment-ktx:2.2.2'
implementation 'androidx.navigation:navigation-ui-ktx:2.2.2'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
//Circular images
implementation 'de.hdodenhof:circleimageview:3.1.0'
//Room database
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
def coroutines_version = "1.3.0"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
}
Your imports say:
import kotlinx.coroutines.internal.synchronized
Which is the internal API that it is complaining about. You should not be importing anything for the synchronized keyword, so simply remove that import line.