对 Android Gradle 的 testCompile 和 androidtestCompile 感到困惑

我是测试世界的新手,更是 Android 测试世界的新手。当我在研究机器人电气的时候,有一件事情最让我困惑。有时在网上,我看到人们使用 testCompile关键字在依赖的年级建立脚本时,引用机器人,而其他人使用 androidTestCompile。当然不可能两者都有效?

有人能解释一下这两者之间的区别吗? 在使用 Roboleecric 时,应该使用哪一个?

24224 次浏览

Simply testCompile is the configuration for unit tests (those located in src/test) and androidTestCompile is used for the test api (that located in src/androidTest). Since you are intending to write unit tests, you should use testCompile.

Update: The main distinction between the two is the test sourceset runs in a regular Java JVM, whereas the androidTest sourceset tests run on an Android device (or an emulator).

To answer your question - Use testCompile for robolectric

why, because robolectric runs on the JVM mocking all the android device behaviour.

testCompile and androidTestCompile are "by convention" android folders which gradle uses while running tasks provided by android plugin.

androidTestDebug picks tests from androidTest folder, testDebug picks tests from test folder,

Again these are only by convention folders you can give source sets for these configurations

Note: espresso is such an awesome library try to move away from robolectric :)

//unit testing

testCompile 'junit:junit:4.12'

The above code is a dependency of JUnit 4 in build.gradle file in android studio. You see that it has testCompile, beacuse JUnit runs on JVM and does not require a device or emulator to run. That also means that JUnit tests will not require the application context to run and if they require we would need to "MOCK" them.

//Insturmented Unit Testing

androidTestCompile('com.android.support.test:runner:0.5', {
exclude group: 'com.android.support', module: 'support-annotations'
})

Now we see androidTestCompile here, because this time we intend to use the device or emulator for tests, that is Instrumentation testing. For beter clarification I would suggest to read from developer.android.com

To add Dependency for JVM testing or Unit testing (testing those rely only on java environment, we don’t need any android environment).

We Use testCompile directive. Example:

dependencies {
testCompile gradleTestKit()
}

To add Dependency for Instrumentation test (Those testing mainly rely on Android environment), we use the androidTestCompile directive.