2

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: enter image description here

Adrian Pascu
  • 949
  • 5
  • 20
  • 48

1 Answers1

3

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"
maryam
  • 1,437
  • 2
  • 18
  • 40
  • I added this dependencies, but still getting the same error. – Adrian Pascu Jul 02 '20 at 06:56
  • Please insert a screenshot of your code where dependecy not resolved – maryam Jul 02 '20 at 09:01
  • I just added the screenshot – Adrian Pascu Jul 02 '20 at 10:42
  • as a last solution: check gradle of this project: https://github.com/makazemi/Mvvm-Android-Testing-Sample/tree/develop. All dependency of test stuff is available inside it.remove your test dependency and past these. – maryam Jul 02 '20 at 15:16
  • Ok, thanks for that. The errors are gone. I am really curious what was the problem, since only copying the missing dependencies didn't work and I really had to replace all my dependencies with the ones in the project you provided. But now I get this error message: ` java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation. at androidx.test.platform.app.InstrumentationRegistry.getInstrumentation(InstrumentationRegistry.java:45) at androidx.test.core.app.ApplicationProvider.getApplicationContext(ApplicationProvider.java:41)` – Adrian Pascu Jul 03 '20 at 14:11
  • Alright, fixed the error. I hope that there will be a time when the Android documentation will actually contain all the information that you need. Anyways, thanks for the help! – Adrian Pascu Jul 03 '20 at 14:35
  • For anyone who might come across this post, also have a look at these two other posts: https://stackoverflow.com/questions/53595837/androidx-no-instrumentation-registered-must-run-under-a-registering-instrumen and https://stackoverflow.com/questions/58516687/how-to-add-java-9-to-android-studio – Adrian Pascu Jul 03 '20 at 14:37