Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute some code when gradle is building the tests

Tags:

gradle

kotlin

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.

like image 706
Brais Gabin Avatar asked Aug 19 '17 18:08

Brais Gabin


People also ask

How do I run a specific unit test in Gradle?

single system property can be used to specify a single test. You can do gradle -Dtest. single=ClassUnderTestTest test if you want to test single class or use regexp like gradle -Dtest. single=ClassName*Test test you can find more examples of filtering classes for tests under this link.

How do you run a test case using Gradle command?

Use the command ./gradlew test to run all tests.


2 Answers

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.

like image 101
punchman Avatar answered Nov 19 '22 23:11

punchman


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.

like image 21
Strelok Avatar answered Nov 20 '22 01:11

Strelok