A project that helps us generate the test project to test the Gradle plugin.

Overview

Ktlint Gradle

Provides the function to generate a Gradle project for us to test your Gradle plugin

Latest plugin version: [1.0.0]

Table of content

How to use

Simple setup

Compile

Kotlin
repositories {
    mavenCentral()
}
dependencies {
    testImplementation(project(":test-toolkit"))
}

Using GradlePluginTest to use DSL to generate your test project

Kotlin
class TemplatePluginTest : GradlePluginTest() {
    private fun testProjectSetup(closure: TemplatePluginTest.() -> Unit) {
        kotlinAndroidTemplate {
            template {
                plugins {
                    id("com.test.plugin").version(File("../VERSION_CURRENT.txt").readText().trim())
                }
                dependencies {
                    implementation("androidx.core:core-ktx:1.7.0")
                    implementation("androidx.appcompat:appcompat:1.4.1")
                }
            }
        }
        TemplatePluginTest().apply(closure)
    }

    @Test
    fun buildTest() {
        testProjectSetup {
            build(":app:prebuild") {
                Assertions.assertEquals(TaskOutcome.SUCCESS, task(":app:prebuild")?.outcome)
            }
            build(":app:lint") {
                Assertions.assertEquals(TaskOutcome.FAILED, task(":app:lint")?.outcome)
            }
        }
    }
}

Case1 using default DSL to generate your test project

Kotlin
androidProject {
    module("app") {
        sourceDir("com.test") {
            file("Main.kt") {
                """
                fun main(){
                    println("Hello world")
                }
                """.trimIndent()
            }
        }
    }
    settingGradle {
        """
        pluginManagement {
            repositories {
                gradlePluginPortal()
                google()
                mavenCentral()
            }
        }
        """.trimIndent()
    }
    gradleProperties { "android.useAndroidX=true" }
}

Case2 Mix the DSL with an existed project

Kotlin
androidProject("src/test/inputs/test-app") {
    module("app") {
        kotlinSourceDir("test") {
            file("Main.kt") {
                """
                fun main(){
                    println("Hello world")
                }
                """.trimIndent()
            }
        }
    }
}
Assertions.assertTrue(File(projectDir, "app/src/main/kotlin/test/Main.kt").exists())
Assertions.assertTrue(File(projectDir, "app/build.gradle").exists())

Case3 Use the default template DSL to generate an android project

Kotlin
androidTemplateKts {
    template {
        `package` {
            name = "test-app"
            packageName = "com.android.test"
        }
        build {
            targetSdk = 31
            targetSdk = 31
            minSdk = 21
        }
        properties {
            property("android.useAndroidX=true")
        }
        repositories {
            repo("google()")
            repo("mavenCentral()")
        }
        plugins {
            id("com.android.application").version(androidVersion())
            id("org.jetbrains.kotlin.android").version(kotlinVersion())
        }
        dependencies {
            implementation("androidx.core:core-ktx:1.7.0")
            implementation("androidx.appcompat:appcompat:1.4.1")
        }
    }
}

Samples

Optionally apply plugin to all project modules:

Kotlin
class TemplatePluginTest : GradlePluginTest() {

    private fun testProjectSetup(closure: TemplatePluginTest.() -> Unit) {
        kotlinAndroidTemplate {
            template {
                plugins {
                    id("com.test.plugin").version(File("../VERSION_CURRENT.txt").readText().trim())
                }
                dependencies {
                    implementation("androidx.core:core-ktx:1.7.0")
                    implementation("androidx.appcompat:appcompat:1.4.1")
                }
            }
        }
        TemplatePluginTest().apply(closure)
    }

    @Test
    fun buildTest() {
        testProjectSetup {
            build(":app:processDebugResources") {
                Assertions.assertEquals(TaskOutcome.SUCCESS, task(":app:processDebugResources")?.outcome)
            }
            build("compileDebugJavaWithJavac") {
                Assertions.assertEquals(TaskOutcome.SUCCESS, task(":app:compileDebugJavaWithJavac")?.outcome)
            }
        }
    }
}
  • test-plugin - A Gradle plugin uses the test-toolkit to do the integration testing.

Code style

We use ktlint to help us format the code. You can use the tasks below to check your code before commit

addKtlintCheckGitPreCommitHook - adds Git pre-commit hook, that runs ktlint check over staged files. addKtlintFormatGitPreCommitHook - adds Git pre-commit hook, that runs ktlint format over staged files and adds fixed files back to commit.

FAQ

  • Why we need it?

    It's tough to test the Gradle plugin and especially with Gradle 7.0. When we use gradleTestKit() we are facing several problem.

    • Can not debug the Gradle plugin
        GradleRunner.create()
          .withProjectDir(projectDir)
          .withGradleVersion(gradleVersion)
          .withDebug(true)
          .forwardOutput()
      • Can not load the kotlin and android build-tool(The class in different class loader.)

        FAILURE: Build failed with an exception.
        
        * What went wrong:
          com/android/build/gradle/AppExtension
        > com.android.build.gradle.AppExtension
        * Try:
        Run with --info or --debug option to get more log output. Run with --scan to get full insights.
        * Exception is:
           java.lang.NoClassDefFoundError: com/android/build/gradle/AppExtension
           at com.github.jackchen.test.gradle.plugin.TemplatePlugin.apply(TemplatePlugin.kt:15)
           at com.github.jackchen.test.gradle.plugin.TemplatePlugin.apply(TemplatePlugin.kt:7)
        ...
        
      • We may need a simple repo for us to test.

Links

Ktlint Gradle Plugin on the Gradle Plugin Registry

You might also like...
A Kotlin library used to analyse discrete Markov chains, in order to generate plausible sequences

Markov Markov is a Kotlin library used to analyse discrete Markov chains, in order to generate plausible sequences. Using This project is still under

FizzBuzzKotlin - A function fizzBuzz to generate a list of string based on the input number

FizzBuzzKotlin write a function fizzBuzz to generate a list of string based on t

Ktorm KSP extension to help generate boilerplate code.
Ktorm KSP extension to help generate boilerplate code.

Ktorm KSP extension to help generate boilerplate code. It can automatically generate Table objects through entity classes, while making entities defined by data classes easier to use, and supports custom extension code generation logic.

🎲 Kotlin Symbol Processor to auto-generate extensive sealed classes and interfaces for Android and Kotlin.
🎲 Kotlin Symbol Processor to auto-generate extensive sealed classes and interfaces for Android and Kotlin.

SealedX 🎲 Kotlin Symbol Processor to auto-generate extensive sealed classes and interfaces for Android and Kotlin. Why SealedX? SealedX generates ext

A ksp library to automatically generate navigation functions for jetpack compose.
A ksp library to automatically generate navigation functions for jetpack compose.

Compose/Navigation/Generator ⚠️ This library is still under development and not considered stable! Content Introduction Usage Example: Single destinat

KotlinScript that generate Reel from a given image, text and audio

ReelScriot KotlinScript that generate Reel from a given image, text and audio 80f4ea39-a7da-4f21-b0ff-7a17836a1cd0.mp4 6691b51d-d7a3-4915-ae41-8bec400

Plannr is an organizational platform developed using Java, in the form of an Android app, that helps university students coordinate their everyday routine.
Plannr is an organizational platform developed using Java, in the form of an Android app, that helps university students coordinate their everyday routine.

Plannr Plannr is an organizational platform developed using Java, in the form of an Android app, that helps university students coordinate their every

A simple android library which helps you to create a curved bottom navigation

CurvedBottomNavigation A simple android library which helps you to create a curved bottom navigation DEMO Setup Update your module level build.gradle

SeatBookView is an Android Studio Library that helps to make it easier to create Bus, Train, Cinema Theater Seat UI and all functionalities are given.
SeatBookView is an Android Studio Library that helps to make it easier to create Bus, Train, Cinema Theater Seat UI and all functionalities are given.

SeatBookView SeatBookView is an Android Studio Library that helps to make it easier to create Bus 🚍 , Train 🚉 , Cinema Theater Seat UI and all funct

Releases(1.0.0)
Owner
Jack Chen
Jack Chen
Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin Gradle DSL.

SampleCompose Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin

Mohammadali Rezaei 7 Nov 28, 2022
A project aiming to generate KMP declarations from several library versions

kotlin-ketchup A project aiming to generate KMP declarations from several library versions LICENSE Apache 2.0. See ./LICENSE in this repository See th

Eugene Petrenko 4 Mar 1, 2022
An introductory dynamics to Test Driven Development (TDD)An introductory dynamics to Test Driven Development (TDD)

tdd-demo Nesse hands-on teremos uma dinâmica introdutória a Test Driven Development (TDD), ou desenvolvimento orientado por testes. instruções 1 - Clo

Plataforma Impact 1 Jan 15, 2022
Gha-central-test - GitHub Actions Maven Central Test

GitHub Actions Maven Central Test Pushing a tag does a release. Local Maven Depl

James Ward 1 Jan 19, 2022
Gradle plugin to manage tests which should only run nightly and not every time a CI/CD pipeline builds.

NightlyTestsPlugin Gradle Plugin to configure which (j)Unit tests should only be run nightly and not everytime a CI/CD pipeline is triggered. Usage To

VISUS Health IT GmbH 0 Dec 7, 2021
Gradle plugin for Hugo static site generator

gradle-hugo-plugin Wrapper for Hugo static site generator. The plugin provides a declarative approach for the Hugo binary used to build the static sit

François Staudt 10 Jun 28, 2022
A multiversion gradle scala plugin

WIP Work in Progress: Learning how to write a gradle plugin. A Scala multiversion plugin Inspired by: https://github.com/ADTRAN/gradle-scala-multivers

Ross Lawley 1 Dec 8, 2021
Gradle plugin which allows to use typed DSL for generating kubernetes/openshift YAML files

gr8s Gradle plugin which allows using typed DSL for generating kubernetes/openshift YAML files. Based on kuberig Usage import io.github.guai.gr8s.Gene

null 0 Jan 3, 2022
A Gradle plugin providing various utility methods and common code required to set up multi-version Minecraft mods.

Essential Gradle Toolkit A Gradle plugin providing various utility methods and common code required to set up multi-version Minecraft mods via archite

Essential 29 Nov 1, 2022
Used to generate the template code of GetX framework

Language: English | 中文简体 statement some fast code snippet prompt come from getx-snippets-intelliJ Description install Plugin effect Take a look at the

小呆呆666 242 Dec 30, 2022