This page is obsolete and not maintained. Instead see Getting Started with Testing and other pages linked below. How it worksUnit tests run on a local JVM on your development machine. Our gradle plugin will compile source code found in
src/test/java and execute it using the usual Gradle testing mechanisms. At runtime, tests will be executed against a modified version of android.jar where all final modifiers have been stripped off. This lets you use popular mocking libraries, like Mockito.You will have to specify your testing dependencies in the build.gradle file of your android module. For example:
dependencies { testCompile 'junit:junit:4.12' testCompile "org.mockito:mockito-core:1.9.5" } Setting up Android StudioTo use unit testing support in AS, see https://developer.android.com/studio/test/index.html Running from Gradle To run your unit tests, just execute the test task: ./gradlew test --continue . If there are some failing tests, links to HTML reports (one per build variant) will be printed out at the end of the execution.This is just an anchor task, actual test tasks are called testDebug and testRelease etc. If you want to run only some tests, using the gradle --tests flag, you can do it by running ./gradlew testDebug --tests='*.MyTestClass' .Because test is just a shorthand for "testDebug testRelease" , the --continue flag is needed if you want to make sure all tests will be executed in all build combinations. Otherwise Gradle could stop after testDebug (failing tests cause the task to "fail") and not execute testRelease at all. You can configure the Gradle runner, using the "all" block:
// ... testOptions { unitTests.all { // All the usual Gradle options. jvmArgs '-XX:MaxPermSize=256m' } } }
Flavors and build types supportJust as with production code, you can have unit tests specific for a given flavor or build type. In general we recommend you keep unit tests in the source tree corresponding to the production code tree, that is:
Note that when running tests from Gradle, we will execute tests for every variant of your code. This means that tests will end up executing at least twice (once with the release build of your code, once with the debug build of production code). "Method ... not mocked."The android.jar file that is used to run unit tests does not contain any actual code - that is provided by the Android system image on real devices. Instead, all methods throw exceptions (by default). This is to make sure your unit tests only test your code and do not depend on any particular behaviour of the Android platform (that you have not explicitly mocked e.g. using Mockito). If that proves problematic, you can add the snippet below to your build.gradle to change this behavior:android { // ... testOptions { unitTests.returnDefaultValues = true } } We are aware that the default behavior is problematic when using classes like Log or TextUtils and will evaluate possible solutions in future releases. |
Technical docs >