mardi 23 février 2021

How to test custom gradle plugin both with JUnit and manually in same sample project

My goal is to have this project setup:

example-gradle-plugin
├── build.gradle
└── src
    ├── main
    │   ├── java
    │   │   └── com ....
    └── test
        ├── java
        │   └── example
        │       └── integrationtest
        │           │ # GradleRunner.create().withProjectDir(testProjectPath.toFile()).withPluginClasspath()
        │           └── SimpleProjectRegressionTest.java // 
        └── resources
            └── simple
                │   # plugins { id "example-gradle-plugin" }
                ├── build.gradle 
                │   # // includeBuild ../../../../example-gradle-plugin
                └── settings.gradle

So the folder src/test/resources/simple is both used from a JUnit test, but as well can be used to run gradle commands from the command line using the composite build approach.

So this should work

cd src/test/resources/simple
gradle build

And this unit test should also work:


    @Test
    public void testBuildSample() {
        final ClassLoader classLoader = ProjectSetupHelper.class.getClassLoader();
        final Path sampleSourceRootPath = Paths.get(classLoader.getResource("simple").toURI());

        final BuildResult result = GradleRunner.create()
                .withProjectDir(sampleSourceRootPath.toFile())
                .withArguments("build")
                .withPluginClasspath()
                .build();
    }

However, there is a caveat when running JUnit, the custom-plugin-sources are referred to in 2 different ways at the same time:

  • GradleRunner.create().withProjectDir(testProjectPath.toFile()).withPluginClasspath() means to add project custom plugin files to the classpath for running the build during the unit test
  • In src/test/resources/simple/settings.gradle, the includeBuild ... command also refers to the custom plugin.

Currently this approach seems to work for me, but is there an easier or cleaner way to achieve the above: Having a sample project with composite build that can be used from the commandline to verify local changes to the plugin, and using that sample project also in a unit test of the plugin?

Aucun commentaire:

Enregistrer un commentaire