且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在单元测试中以编程方式调用Gradle任务图

更新时间:2023-02-20 21:08:36

在我看来,你试图在这里得到的是比单元测试更多的集成测试。 Gradle团队成员过去曾经向我建议,在编写插件和执行任务时,你想要做的就是尽可能多地分离/从你的任务中分离出来,并将其分解为POJO和单元测试。对于Gradle为你做的所有其他事情以及管道工作,比如执行任务图,测试增量任务特性等等,你可能想要进行集成测试,这肯定比较慢,这就是为什么你想尽可能地进行单元测试的原因。 p>

唯一的问题是Gradle目前不提供用于编写​​这些集成测试的工具集。有一个设计规范,但目前你如果您需要的话,仍然需要手工制作解决方案。



您可以看看我使用的这里,但请记住它有一些classpath问题,这就是为什么这一行是必需的。



另一个使用GradleConnector并且我最近发现的解决方案的例子可以找到这里 a>。


I am in the process of writing a custom plugin for gradle and as part of the unit testing I would like to invoke my task but in such away as it's prerequisite tasks are executed.

The actual plugin is unfortunately an internal project so I can't sure the exact source, but I have prepared a unit test that demonstrates the problem:

package toy

import org.gradle.api.Project
import org.gradle.testfixtures.ProjectBuilder
import org.junit.Test

class ToyTasksTest {

    boolean task1Run = false
    boolean task2Run = false

    @Test
    public void taskDependencies(){


        Project p = ProjectBuilder.builder().build()

        p.task("task1") << {
            p.logger.info("task1 running")
            task1Run = true
        }

        def task2 = p.task("task2", dependsOn: 'task1') << {
            p.logger.info("task2 running")
            task2Run = true
        }
        task2.execute() // <--- what magic do I need here instead of .execute()

        assert task2Run == true
        assert task1Run == true
    }
}

The output is:

Assertion failed: 

assert task2Run == true
       |        |
       false    false

The project is available on github if you would like to quickly run the test.

Another way of saying this instead of writing:

task2.execute()

I'd like run the equivalent of:

gradle task2

In the unit test.

It seems to me that what you are trying to get here is more of an integration test than a unit test. It was suggested to me in the past by Gradle team members that when writing plugins and task what you want to do is to separate as much as you can/makes sense from your task into POJO and unit test that. For everything else that Gradle does for you and the plumbing, like executing task graph, testing incremental task features and so on you probably want to have integration tests which definitely are slower, that's why you want to unit test as much as possible.

The only problem is that Gradle currently doesn't provide a toolset for writing those integration tests. There is a design spec for that but currently you still have to hand craft a solution if you need one.

You can have a look the one that I using here but keep in mind that it has some classpath issues, that's why this line is necessary.

An example of the other solution that is using GradleConnector and that I found recently can be found here.