如何在单元测试中运行我的自定义gradle任务?

wdebmtf2  于 2023-01-31  发布在  其他
关注(0)|答案(1)|浏览(154)

我需要运行gradle任务来测试单元测试中的基本功能:

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

public class IwillfailyouPluginTest {
    @Test
    public void applyPlugin() {
        final Project project = ProjectBuilder.builder().build();
        project.getPlugins().apply(IwillfailyouPlugin.class);
        project.task("iwillfailyou").// what method should I run?
    }
}

但是我找不到运行它的方法,请帮帮我

mkshixfv

mkshixfv1#

我的理解是ProjectBuilder更多的是用于类似单元的测试,所以对于您所拥有的,您应该只Assert一个名为iwillfailyou的任务存在,是某种类型的,并且具有正确的配置。

public class IwillfailyouPluginTest {

    @Test
    public void applyPlugin() {
        final Project project = ProjectBuilder.builder().build();
        project.getPlugins().apply(IwillfailyouPlugin.class);
        
        assertTrue(project.getTasks().getNames().contains("iwillfailyou"));
        
        MyCustomTaskType iwillfailyou = project.getTasks().getByName("iwillfailyou");

        assertEquals(123, iwillfailyou.getSomeConfig())
    }

}

看起来你正在尝试测试自定义任务的行为/功能。对于这种测试,你可以使用TestKit

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.io.FileWriter;
import java.nio.file.Files;

import org.gradle.testkit.runner.GradleRunner;
import org.gradle.testkit.runner.BuildResult;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class IwillfailyouPluginFunctionalTest {

    @Test
    void canRunTask() throws IOException {
        // Setup the test build
        File projectDir = new File("build/functionalTest");
        Files.createDirectories(projectDir.toPath());
        writeString(new File(projectDir, "settings.gradle"), "");
        writeString(new File(projectDir, "build.gradle"), "plugins {" + "  id('i.will.fail.you')" + "}");

        // Run the build
        GradleRunner runner = GradleRunner.create();
        runner.forwardOutput();
        runner.withPluginClasspath();
        runner.withArguments("iwillfailyou");
        runner.withProjectDir(projectDir);
        BuildResult result = runner.build();

        // Verify the result
        Assertions.assertTrue(result.getOutput().contains("someoutput from the iwillfailyou task"));
    }

    private void writeString(File file, String string) throws IOException {
        try (Writer writer = new FileWriter(file)) {
            writer.write(string);
        }
    }
}

相关问题