简体   繁体   中英

Test for created file with Spock in Gradle

I have task which generates picture, so I want to write test for it that compares this picture binary with picture previously generated in the resource folder.

def setupSpec() {
   project = ProjectBuilder.builder().build()
   generatePicTask = project.tasks.create(SomePlugin.GENERATE_PIC_TASK_NAME, GeneratePicTask)
}

def 'create Picture test'() {
 when:
   File fileName = new File("Info")
 then:
    generatePicTask.createPicture(fileName)
 expect:
    fileName.exists()==true
}

But there is error that

C:\Users\User\AppData\Local\Temp\gradle1393280218367058727projectDir\build\Info.PNG 
(The system cannot find the path specified)

The picture is generated in the the action closure in the task generatePicTask .

The project object is dummy project so I don't know even it was executed. How I can fix this?

I see 3 problems with your current approach:

Your test shouldn't rely on the current working directory. Therefore instead of creating a file like this:

File fileName = new File("Info")

use a junit TemporaryFolder rule for example. have a look at with using eg http://garygregory.wordpress.com/2010/01/20/junit-tip-use-rules-to-manage-temporary-files-and-folders/ for more details

It seems GeneratePicTask task not generate the 'build' directory

Ensure that the output directory (the parent folder of the created image exists). You can use gradle annotations eg @OuputDirectory to let gradle take care of that. otherwise before generating your image do something like 'fileName.parentfile.mkdirs'

In general the way to go is to split the configuration of your task and task execution:

generatePicTask.setPicture(fileName)
generatePicTask.create() // your @TaskAction annotated method

cheers, René

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM