Support classes for unit testing custom tasks in custom plugin are gradle internal?


(Matias Bjarland) #1

I am writing spock unit tests for custom tasks in my custom plugin. I would like to do something similar to the following excerpt from the gradle source:

...
import spock.lang.Specification
  class GeneratorTaskTest extends Specification {
    ...
    final GeneratorTask<TestConfigurationObject> task = HelperUtil.createTask(GeneratorTask)

where the last line uses HelperUtil.createTask to mock up a project in a temporary directory and return a functioning task object you can use to execute your spock specification against. This looked really promising until I realized that the HelperUtil class is gradle internal. Internal as in the class does not seem to be part of the gradle distribution and only used for internal testing purposes.

It should be mentioned that just doing a “new TaskClass()” on the task I want to test results in an assertion failure from gradle:

java.lang.AssertionError
 at org.gradle.api.internal.AbstractTask.taskInfo(AbstractTask.java:101)
 at org.gradle.api.internal.AbstractTask.<init>(AbstractTask.java:96)
 at org.gradle.api.DefaultTask.<init>(DefaultTask.java:31)
        ...

caused by a ThreadLocal<TaskInfo> which is not set. TaskInfo itself is a gradle internal class at which point it starts getting a bit hairy.

In the face of the above, any suggestions as to what the best way to go about testing your custom tasks would be?

Could we pull in some of these internal support classes when specifying the:

...
dependencies {
   groovy gradleApi()
  ...
}
...

dependency? I mean in this situation we have already declared that we are writing something which integrates directly with the external APIs of gradle. Would it not be prudent to assume that such a project would be interested in the classes needed to run tests on the code written?

I am assuming I’m probably missing something here as I would guess that others writing plugins must have faced (and solved) this issue.


(Peter Niederwieser) #2

As you said, HelperUtil is internal. You should use org.gradle.testfixtures.ProjectBuilder instead.


(Matias Bjarland) #3

Thank you, that solved my problem.