Search code examples
gradlegroovy

Run script before unit tests


For my for Android app's unit and instrumented tests, I need certain files to exist on disk. I've created a Python script which generates them. However, I'm having trouble modifying my app's build.gradle file to run the script before my tests. Based on some examples I saw, I tried

task generateFile(type: Exec) {
    onlyIf { !file('app/src/test/resources/needed_file').exists() }
    commandLine 'python3', 'scripts/generate_test_files.py'
}

testDebugUnitTest.dependsOn generateFile

However, I get the error

Could not get unknown property 'testDebugUnitTest' for project ':app' of type org.gradle.api.Project.

I've tried several variations such as test.dependsOn generateFile but all of them give similar errors.


Solution

  • Wildly guessing that testDebugUnitTest task is generated later in some afterEvaluate action or similar, try to be a bit more reactive. If the guess is right, this should help:

    tasks
        .matching { it.name == "testDebugUnitTest" }
        .configureEach { dependsOn(generateFile) }