androidgradledependenciesandroid-espressoandroid-testing

Test Error - NoClassDefFoundError: Failed resolution of: Lorg/hamcrest/Matchers


I am using Espresso for Instrumented Test but got this error on the Stack Trace:

enter image description here

The error being caused by a missing class as shown below:

Caused by: java.lang.ClassNotFoundException: Didn't find class "org.hamcrest.Matchers" on path: DexPathList[[zip file "/system/framework/android.test.runner.jar", zip file "/system/framework/android.test.mock.jar", zip file "/system/framework/android.test.base.jar", zip file "/data/app/~~vnZzxGNKnS4V6YkEf4falA==/com.example.android.architecture.blueprints.reactive.test-K_x0_yJ0hJeDHaJkDmHXRw==/base.apk", zip file "/data/app/~~oeYx2MgTcILbk-vq_WPx1A==/com.example.android.architecture.blueprints.reactive-0wMHYEe95hx_1cnbdAoZAw==/base.apk"],nativeLibraryDirectories

It first occurred immediately after I added this code in the Fragment Test:

enter image description here

These are my relevant Libs on the Gradle:

enter image description here

I have these imports:

import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.hamcrest.core.IsNot.not

Solution

  • TLDR answer, you don't need to downgrade the whole espresso setup there is a Hamcrest version conflict with transitive dependencies which can be easily solved:

    If you are using:

    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.4.0'
    
    //change it to:
    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.3.0'
    

    if you are using:

    androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.4.0'
    
    //change it to:
    androidTestImplementation "androidx.test.espresso:espresso-accessibility:3.3.0"
    

    You should still be able to keep espresso core at the higher 3.4.0 version


    If you want to understand, here is the longer explanation:

    To see what is going on under the hood we can use the dependencies gradle task to print out the dependency tree, in android studio terminal:

    ./gradlew :app:dependencies
    

    We can run it twice, using the dependencies at the two version levels and can check the differences.

    [Gradle dependency tree comparison1