Obviously I need the correct import statment to solve this problem. According to the docs for AndroidJUnit4, this should be
import android.support.test.runn
Make sure you have
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
dependency in your app build.gradle file. I deleted it by mistake and test stopped wroking.
Adding
compile com.android.support.test:runner:0.5'
resolved this exact issue for me.
Short Story Version:
Upgrade your Gradle to the latest Version
I am answering this question post on Feb, 15th, 2020. Unfortunately, I have exhausted every possible solutions mentioned here and elsewhere.
https://github.com/codepath/android_guides/wiki/UI-Testing-with-Espresso
https://github.com/udacity/AdvancedAndroid_TeaTime/issues/14
Android Espresso : cannot resolve symbol AndroidJUnit4.class
Cannot resolve symbol AndroidJUnit4
Android Espresso : cannot resolve symbol AndroidJUnit4.class
Yes, none of them above workes. I use the built-in function, "Migrate to Andoridx", it may remind me that I have to upgrade my target SDK versions and my gradle version. After I upgraded my gradle version from 2.0.2 to 3.5.3. They just works, even the old import statement works.
Ok so here is your mistake and mine!
If we are going to write a pice of code for Local Unit Testing we shouldn't use @RunWith(AndroidJUnit4.class)
cause we do not use AndroidJUnit4 but we need Junit4. so we should write @RunWith(JUnit4.class)
. And of course your java test file is under app/src/test/java/your.package.name
directory.
Else if (!!) we want to write some Android Instrumented Unit Test we should put our test java files in app/src/androidTest/java/your.package.name
directory and use annotation like @RunWith(AndroidJUnit4.class)
The common cause of this problem is that when adding below dependency:
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
This is a correct dependency if you are going to use instrumented tests (tests in the androidTest
java package)
But for implementing local unit tests (tests in test
java package) while using above mentioned dependency; then you'll face Cannot resolve symbol 'AndroidJUnit4'
That is because androidTestImplementation
directive is used to import libraries in instrumented tests, but not in the local JVM/unit tests.
If you want to use AndroidJUnit4
in a local JVM/unit test, then use below dependency instead
testImplementation 'androidx.test.ext:junit:1.1.1'
The same thing applies if you add the latter dependency while using AndroidJUnit4
in instrumented test, you will also get Cannot resolve symbol 'AndroidJUnit4'
; because you're using the wrong directive.
If you're using project with multiple build-type then the selected build-type in build-variant window must be mentioned with testBuildType tag in module's build.gradle file.
For e.g.: If you're using build type debug then you should add android{testBuildType "debug" }
, if using stage then add android{testBuildType "stage"}
statement in android tag.