`testImplementation` does not seem to resolve the dependencies correctly for tests

Viewed 564

I am working in some Unit Tests (not instrumented) in Android Studio. All my test dependencies have been declared in my 'build.gradle' like this:

testImplementation 'junit:junit:4.12'
testImplementation "org.mockito:mockito-core:$mockitoVersion"
testImplementation "org.powermock:powermock-module-junit4:$powerMockVersion"
testImplementation "org.powermock:powermock-api-mockito2:$powerMockVersion"
testImplementation 'org.json:json:20140107'
testImplementation 'org.robolectric:robolectric:3.4.2'

However, when I load a test file, all the dependencies are marked as "Cannot resolve symbol XXX". If I change it from testImplementation to androidTestImplementation, all dependencies are detected correctly. However these are not instrumented tests, but independent unit tests, so when I execute the tests with androidTestImplementation it returns a error: package org.junit does not exist, preventing me from running the unit tests. Things that I have checked so far (from many stackoverflow answers):

  • Ensure my tests are in the test folder, and not in androidTest
  • Delete .idea and .gradle folder
  • Remove dependencies, sync gradle, re declare dependencies, re sync.
  • Invalidate caches and restart (several times).
  • Try with Android Studio 4.0 (currently 3.6)
  • Re import project from scratch.

Also it is important to note (or maybe not) that the project is a library and not an application.

As a workaround, I have declared the dependencies as implementation so I can continue running tests locally, but of course this is bothering and dangerous as I do not want to end up shipping my AAR with testing dependencies by mistake.

1 Answers

A late answer, but maybe it will help people who come across this question and struggle with the same issue.

What worked for me was to set the sourceSets in build.gradle (in the android brackets) to the correct directory, at first I had a different configuration but the one below worked for me and let me import JUnit to my test class

sourceSets {
    test.java.srcDirs += 'src/test/java'
}
Related