Brais Gabin
Brais Gabin

Reputation: 5935

How to execute some code when gradle is building the tests

Kotlin have a compiler plugin called all open. It forces that all the classes with some annotations are open.

I want to use this feature for my tests but I don't want it in my production code (I want my classes closed). How can I do this?

I tried something like:

test {
  allOpen {
    annotation('com.my.Annotation')
  }
}

But the code is execute always.

Upvotes: 10

Views: 2011

Answers (3)

punchman
punchman

Reputation: 1380

I think, that you can do so:

android.applicationVariants.all { ApplicationVariant variant ->
    boolean hasTest = gradle.startParameter.taskNames.find {it.contains("test") || it.contains("Test")} != null
    if (hasTest) {
        apply plugin: 'kotlin-allopen'
        allOpen {
            annotation('com.my.Annotation')
        }
    }
}

Then you will not need to pass a property when running the test.

Upvotes: 7

mlykotom
mlykotom

Reputation: 5155

I had exactly same issue - wanted to have opened classes only for tests because of mocking. I didn't want to use custom parameter, because the code is running locally, on CI and therefore would need to be setup everywhere.

Found solution for it - checking whether task name contains test:

def isTestTask = getGradle().getStartParameter().getTaskNames().any {name -> name.contains("test")}

if (isTestTask) {
    apply plugin: 'kotlin-allopen'
    allOpen {
        annotation('com.my.Annotation')
    }
}

You may try if it would suit you better :)

Upvotes: 0

Strelok
Strelok

Reputation: 51451

It happens because the plugin is applied in the root of the build.gradle file.

A solution that will 100% work is to not apply the plugin unless some project property is set.

if (project.hasProperty("allopen")) {

  apply plugin: "kotlin-allopen"

  allOpen {
    annotation('com.my.Annotation')
  }

}

and run test with the property: gradle -Pallopen test.

Maybe some Gradle gurus can chime in with a better solution.

Upvotes: 14

Related Questions