简体   繁体   中英

Running unit tests of a plain Java project in Android Studio with Gradle

In a multi-module Android project, I have a plain Java project that other Android libraries and applications depend on. I recently migrated the entire project to build using Gradle.

I have a problem running the junit tests of the plain Java project, only in Android Studio. On the command line the tests are running fine:

./gradlew -p the-java-proj test

This executes the unit tests as expected, if I insert a Assert.fail() as a sanity check, I correctly get the expected failure.

However, I cannot manage to run the unit tests in Android Studio. I created a run configuration to run all tests in the package, and I get this error when running:

Error running MYTESTNAME: No junit.jar in Module 'MYMODULENAME' runtime scope

That "runtime scope" at the end is fishy, but I don't know what I'm supposed to do with that. Here's the build.gradle of the project:

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    testCompile 'junit:junit:4.11'
    testCompile 'org.mockito:mockito-all:1.9.5'
}

This is especially puzzling because I could run unit tests fine in Android Studio before migrating to Gradle. Only now I have such problem. I also don't get friendly context menu options to run individual unit tests. And, as far as I remember, the keyboard shortcut to run unit tests in the current file used to work before, now it just pops up the run configuration chooser with no option to add new.

If you attach a java project to android project, when run tests from main project it will not run tests in java library project. what it only do is create the jar of the library project. So we need to explicitly tell to run test task.

apply plugin: 'java'

repositories {
mavenCentral()
}

dependencies {
   testCompile 'junit:junit:4.11'
   testCompile 'org.mockito:mockito-all:1.9.5'
}

jar.dependsOn test

From this article: https://coderwall.com/p/ybds4w (thanks to @GalBenHaim )

However, if you need to use JUnit for POJO testing exclusively or using popular frameworks then there is no integrated support yet in Android Studio.

In other words, at the time I write this, Android Studio cannot do this, I cannot run my JUnit tests on POJOs. On the command line it works fine ( ./gradlew test ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM