Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test afterEvaluate when writing Gradle plugin

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!

like image 984
Boris van Katwijk Avatar asked Sep 16 '16 13:09

Boris van Katwijk


1 Answers

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.

like image 83
Aarjav Avatar answered Oct 27 '22 11:10

Aarjav