How can I create a "test" task that builds particular subprojects with a given bootclasspath (e.g. android.jar)?

I would like to have a “test” task that checks if particular subprojects with Java code build against the Android API and runs the unit tests with the android.jar. Right now I have a smack-android subproject which build.gradle defines only the required dependencies, the subproject itself contains no code:

description = """\
Smack for Android.
All the required dependencies to run smack on Android"""
  ext {
 androidProjects = ['smack-tcp','smack-core', 'smack-resolver-minidns', 'smack-sasl-provided', 'smack-extensions', 'smack-experimental']
  // Note that the test dependencies (junit, …) are inferred from the
// sourceSet.test of the core subproject
dependencies {
 androidProjects.each { name ->
  compile project(":$name")
  jar {
 enabled = false
  // TODO Add task buildWithAndroidTest which checks that $androidProjects builds
// with Android Runtime Jar as bootclasspath and runs the unit tests with android.jar
  def getAndroidRuntimeJar() {
 new File("/opt/android-sdk-update-manager/platforms/android-8/android.jar")

So I need to define a task that force builds $androidProjects with the Android Runtime jar and runs the unit tests with android.jar as bootclasspath. How can I create such an task and make smack-android :test depend on it, so that it’s called when I run the test target of smack-android?

The relevant feature branch can be found at

I ended up with

def getAndroidRuntimeJar() {
    def androidHome = new File("$System.env.ANDROID_HOME")
    if (!androidHome.isDirectory()) throw new Exception("ANDROID_HOME not found or set")
    new File("$androidHome/platforms/android-$smackMinAndroidSdk/android.jar")
configure (androidProjects) {
    task compileAndroid(type: JavaCompile) {
        source = compileJava.source
        classpath = compileJava.classpath
        destinationDir = new File(buildDir, 'android')
        options.bootClasspath = getAndroidRuntimeJar()
  test { dependsOn androidProjects*.compileAndroid }