Unit testing custom tasks and if they're up to date

Hi there,

I’ve written a custom gradle task and am trying to unit test it using a groovy JUnit test case. The task has defined inputs and outputs:

public class GetFileTask extends DefaultTask {
    @Input String src;
  @OutputFile File dest;
      @TaskAction
  void downloadDriver(){
   new URL(src).withInputStream{ i -> dest.withOutputStream{ it << i }}
  }
}

and I’d like to check in my unit test that running the task more than once means it gets skipped on subsequent runs as it’s up to date. I have the following test but the task is not marked as skipped on the second run, and it’s still marked as having done some work (task.getState().getDidWork() is true)

Project project
 Task task
   @Before
 void setup(){
    project = ProjectBuilder.builder().build();
  task = project.task("downloadTask", type: GetFileTask )
 }
   @Test
 void testUpToDate(){
  File expected = project.file(OUTPUT_PATH)
  println "expecting download to " + expected.getAbsolutePath()
      //check file doesn't exist before we start
  assertFalse "file already exists", expected.exists()
      task.src=SRC_URL
  task.dest = project.file(OUTPUT_PATH)
  task.execute();
      //check file now exists, task wasn't skipped and that it did some work
  assertTrue "file does not exist", expected.exists()
  assertTrue "task didn't do any work", task.getState().getDidWork()
  assertFalse "task skipped", task.getState().getSkipped()
      //run again and task should be skipped, with no work done
  task.execute();
  assertTrue "file does not exist", expected.exists()
  assertFalse "task did work", task.getState().getDidWork()
  assertTrue "task not skipped", task.getState().getSkipped()
 }

Should I be executing the task differently, or checking different properties to get the results I expect? There doesn’t seem to be a lot of documentation about unit testing custom tasks.

Thanks, Sarah

You won’t be able to unit test up-to-date checking of a task. You will need integration tests for this - essentially up-to-date checking only happens when a real build is executed.

Your best option at the moment for writing integration tests is using the nebula-test plugin: https://github.com/nebula-plugins/nebula-test.