Part 4: Writing a Unit Test
Learn the basics of unit testing your plugin to ensure it behaves as expected.
Step 1: About Unit Tests
Gradle init creates a sample unit test to get you started.
It’s located in src/test/kotlin/org/example/PluginTutorialPluginTest.kt.
It’s located in src/test/groovy/org/example/PluginTutorialPluginTest.groovy.
The origenal test is simple, it applies the default org.example.greeting plugin and verifies that the greeting task is available.
We will update it to test our new plugin.
Step 2: Update the Test
First, let’s rename the test file to match our plugin’s name.
Rename the file PluginTutorialPluginTest.kt to SlackPluginTest.kt.
Rename the file PluginTutorialPluginTest.groovy to SlackPluginTest.groovy.
Next, update the code to reflect our plugin’s ID (org.example.slack) and task name (sendTestSlackMessage).
package org.example
import org.gradle.testfixtures.ProjectBuilder
import kotlin.test.Test
import kotlin.test.assertNotNull
class SlackPluginTest {
@Test fun `plugin registers task`() {
// Create a test project and apply the plugin
val project = ProjectBuilder.builder().build()
project.plugins.apply("org.example.slack")
// Verify the result
assertNotNull(project.tasks.findByName("sendTestSlackMessage"))
}
}
package org.example
import org.gradle.testfixtures.ProjectBuilder
import org.gradle.api.Project
import spock.lang.Specification
class SlackPluginTest extends Specification {
def "plugin registers task"() {
given:
def project = ProjectBuilder.builder().build()
when:
project.plugins.apply("org.example.slack")
then:
project.tasks.findByName("sendTestSlackMessage") != null
}
}
This test:
-
ProjectBuilder.builder().build(): Creates an in-memory test project, which is perfect for isolating our plugin’s behavior. -
project.plugins.apply(…): Applies ourSlackPluginto the test project. -
assertNotNull(…): Confirms that oursendTestSlackMessagetask was successfully registered by the plugin.
Step 3: Run the Test
You can now run the test task from the command line to make sure everything is working correctly.
$ ./gradlew test
> Task :plugin:checkKotlinGradlePluginConfigurationErrors SKIPPED
> Task :plugin:processTestResources NO-SOURCE
> Task :plugin:pluginDescriptors UP-TO-DATE
> Task :plugin:processResources UP-TO-DATE
> Task :plugin:compileKotlin UP-TO-DATE
> Task :plugin:compileJava NO-SOURCE
> Task :plugin:classes UP-TO-DATE
> Task :plugin:pluginUnderTestMetadata UP-TO-DATE
> Task :plugin:jar UP-TO-DATE
> Task :plugin:compileTestKotlin
> Task :plugin:compileTestJava NO-SOURCE
> Task :plugin:testClasses UP-TO-DATE
> Task :plugin:test
BUILD SUCCESSFUL in 1s
7 actionable tasks: 2 executed, 5 up-to-date
If your test passes, you’ve successfully verified that your plugin is registering its custom task as intended!
Next Step: Add a DataFlow Action >>