How do I add a dependency to the android gradle task 'test'?

I’ve introduced a dependency for my unit tests to a custom task I’ve written in gradle. In android-gradle v1.2.3 the unit test task is named test. So I assumed you add a dependency with test.dependsOn. Gradle doesn’t like that.


 Error:(30, 0) Could not find property 'test' on project ':app'.


apply plugin: ''

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.nilzor.myapplication"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile ''

task myTask() {

test.dependsOn 'mytask' 

Where do I go wrong and how do I fix it?

Found that I had to wrap it in

afterEvaluate {       

The test task is obviously created at a later point

A better solution that would continue working in the current versions of Gradle is to make this a rule like so:

tasks.matching('test') {
    dependsOn 'myTask'