Run gradle task X after “connectedAndroidTest” tas

2019-08-08 15:34发布

I have a gradle taskX that I would like to run after connectedAndroidTest task finishes, however only if all tests pass in connectedAndroidTest.

How I can achieve this?

2条回答
祖国的老花朵
2楼-- · 2019-08-08 15:42

You need to utilize finalizedBy along with particular task's state checking. Here's how it can be done:

task connectedAndroidTest << {
  logger.lifecycle("Running $name")
  if (project.hasProperty('lol')) {
    throw new Exception('lol')
  }
}

task taskX << {
  def failure = tasks.connectedAndroidTest.state.failure
  if(!failure) {
    logger.lifecycle("$name is finalizer")
  } else {
    logger.lifecycle("$tasks.connectedAndroidTest.name failed, nothing to do.")
  }
}

connectedAndroidTest.finalizedBy(taskX)

Now if run with:

gradle cAT

the output will be:

:connectedAndroidTest
Running connectedAndroidTest
:taskX
taskX is finalizer

BUILD SUCCESSFUL

Total time: 1.889 secs

This build could be faster, please consider using the Gradle Daemon: https://docs.gradle.org/2.8/userguide/gradle_daemon.html

When:

gradle cAT -Plol

is run, then the output is:

:connectedAndroidTest
Running connectedAndroidTest
:connectedAndroidTest FAILED
:taskX
connectedAndroidTest failed, nothing to do.

FAILURE: Build failed with an exception.

* Where:
Build file '/Users/opal/tutorial/stackoverflow/34797260/build.gradle' line: 4

* What went wrong:
Execution failed for task ':connectedAndroidTest'.
> lol

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 1.931 secs

Here a demo can be found.

  [1]: https://docs.gradle.org/current/javadoc/org/gradle/api/Task.html#finalizedBy(java.lang.Object...)
查看更多
我想做一个坏孩纸
3楼-- · 2019-08-08 16:03

You're describing Task Dependencies. You can define a task that depends on another, and will therefore trigger the other when it is executed:

task taskX(dependsOn: 'connectedAndroidTest') << {
   //do something
}

And then just run your task, and connectedAndroidTest will be execute first:

gradle taskX

Task Dependency docs

查看更多
登录 后发表回答