Test existance of directory in Gradle?
Question
I have directory in which I have to put some results, but the user can configure it If the directory does not exist I have to create it. But now I have to write test for that code.
getOutputPath() is getter method
@Optional
def outputPath = new File('build/sampleDir')
@TaskAction
def generate() {
if (!getOutputPath().exists()) {
project.mkdir(getOutputPath())
}
The creation is in the Action closure so this is executed in the execution phase, but if I try:
...
def 'change default outputPath dir'() {
when:
someTask.outputPath = new File(project.rootProject.buildDir, "newPath")
then:
....
expect:
project.afterEvaluate {
generateQRFromTextTask.getOutputQRPath().exists() == true
}
}
For my surprise this code pass as well the same but with project.gradle.buildFinished {. Without them it fails. Why the test passes with afterEvaluate ?
And what is the best way to make this checks(for directory existing? In constructor or?
Solution
The property should be annotated with @OutputDirectory
, in which case the directory will be created automatically.
PS: Depending on the exact nature of your test, afterEvaluate
may never be triggered.
PPS: A property that has a default value doesn't need to be annotated with @Optional
.