Instant use cases in Unit Test for a custom Gradle plugin that depends on an Android plugin
I am developing a Gradle plugin. My plugin depends on Android Gradle plugin. My plugin adds a task for each android app. Each task name is generated from the variant name.
public class MyPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
project.android.applicationVariants.all {
project.task(type: SendApkTask, dependsOn: it.assemble, "send${it.name.capitalize()}Apk")
}
}
}
I want to create a unit test for MyPlugin # apply (Project). The test should verify that the task has been added. There should only be release and debug options by default.
public class MyPluginTest {
Project project
@Before
public void setup() {
project = ProjectBuilder.builder().build()
}
@Test
public void testMyPluginAddsTasks() {
project.apply plugin: 'com.android.application'
project.apply plugin: MyPlugin
assertNotNull(project.tasks['sendReleaseApk'])
}
}
I cannot convey this statement. After debugging, I found it was project.applicationVariants
empty. My closure adding tasks never starts. How do I get the Android Gradle plugin that mocks my test? Do I need to customize my entire mock directory file with ProjectBuilder
?
source to share
When unit testing units using ProjectBuilder
, it is usually necessary to explicitly call Project.evaluate()
in cases where plugins are used Project.afterEvaluate()
. Add the following before doing the following.
project.evaluate()
The Android Gradle plugin also needs to be installed project.android
or will be thrown away NullPointerException
.
project.android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
}
source to share