Unit tests are awesome. In Android, the built-in unit tests are a kind of a drag because they require an emulator or a phone and APK deploys to the aforementioned device (in other words, they are slow). A popular alternative is Roboelectric. While it’s easy to add Roboelectric as a JAR or Maven dependency, it wasn’t so easy to add as a submodule.
“Why would you want Roboelectric as a submodule?” you ask.
So that you can easily tweak Roboelectric and debug the code right in your Android project. Of course!
There’s an Android Intellij Starter project for adding Roboelectric as a submodule in Intellij. However, I couldn’t get that to work, and besides, it brings too many other libraries that at this point I don’t need. So I did it myself from scratch. The steps below show how I setup Roboelectric as a submodule in my Android Studio (Intellij) project:
- Setup your Android project as you normally would. Use whatever SDK and version of Java you want. (Note: Roboelectric probably doesn’t work with really old versions of the Android SDK.)
- Install Android SDK API 16 (Android 4.1.X) including the corresponding Google APIs (in addition to the libraries used by your project). Roboelectric doesn’t work with API 17. Haven’t tried lower versions.
- Tell Intellij about Maven. Go to Settings >> Maven and set the Maven home directory.
- Tell Maven about the Google APIs:
mvn install:install-file -DgroupId=com.google.android.maps \ -DartifactId=maps \ -Dversion=16_r3 \ -Dpackaging=jar \ -Dfile="$ANDROID_HOME/add-ons/addon-google_apis-google-16/libs/maps.jar"
- (Optional) fork Roboelectric if you plan on contributing changes. (Hey you never know.)
- Add Android SDK API 16 and Java 6 to your project. Go to Project Structures >> SDKs and click the plus sign. Make sure that the Android SDK uses Java 6.
- Do not add Maven Framework Support to your project. If your project already uses maven, that’s fine. Otherwise, don’t add maven support unless you know what you’re doing.
- Setup Roboelectric as a git submodule. From your project directory, run:
git submodule add git://<ROBOELECTRIC_GIT_URL>
where the URL is either to your fork or the Roboelectric git URL.
- Add Roboelectric to your Intellij project as a module. Open the roboelectric folder in the Project View and right click the pom.xml file. Select Add as Maven Project.
- Configure the roboelectric submodule to use Android SDK API 16 (Android 4.1.X). Open Project Structure >> Modules >> roboelectric and change Module SDK to Android 4.1.X.
- Order your project libraries correctly. Go to Project Structure >> Modules >> <YourProject> >> Dependencies and make sure the libraries are in this order:
- Module sources
- android support (optional)