How to test afterEvaluate when writing Gradle plugin
Asked Answered
B

2

13

I am writing a custom Gradle plugin. I am writing tests for every feature that I want to create in the plugin. I am using java to write the plugin.

I create my tasks in the apply method inherited from the Plugin interface.

I have a number of dependencies on tasks that are available in the afterEvaluate stage of the project build lifecycle, but not sooner (at least, not in the apply phase) and I have no control over the way that those external tasks are defined.

So I define the dependencies on those tasks using

project.afterEvaluate((project) -> {
    customTask.dependsOn(project.getTasks().getByName("nameOfTheTask"));
});

In test code I have the following setup, using JUnit and the gradle test kit:

@BeforeClass
public static void initializeProject() {
    project = ProjectBuilder.builder().build();

    customPlugin = new CustomPlugin();
    customPlugin.apply(project);
}

I can check the regular (i.e. outside the afterEvaluate block) dependencies in test cases by retrieving my tasks using

project.getTasks().findByName("customTask").getDependsOn()

This is however not possible for the dependencies defined for a certain lifecycle or, more generally, as a closure.

Is there any way to test whether the correct dependencies are set for a certain lifecycle? Or is there a way to retrieve what was registered such a code block?

P.S. I could use casting, reflection, shadowing, modification etc but I'd really like to hear if this is testable, or maybe I am taking the wrong approach after all. Thanks!

Bosh answered 16/9, 2016 at 13:40 Comment(0)
I
9

I could not find the correct/public api way of doing this, however for gradle 4.3.1 this works for me:

project.getTasksByName("tasks", false); //internally it calls project.evaluate()

Internally the method forces evaluation of the project, and therefore the afterEvaluate hooks are also called.

Indecent answered 30/11, 2017 at 20:19 Comment(1)
Works like a charm, also with gradle 7.2Chronister
C
0

It works for me if I apply the custom plugin like this:

project.getPluginManager().apply(CustomPlugin.class);
Corotto answered 7/3, 2017 at 12:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.