gradle 3.5 do not recognize class from terminal - java

I'm using Intillij with gradle 3.5 and I want to call specific class in project. in me build.gradle I have
ext.testFile = System.getProperty('Test_Plan') ?: 'testng.xml'
test {
ignoreFailures = true
testLogging {
events 'started', 'passed'
}
useTestNG {
suites "src/main/resources/${testFile}"
}
}
that use to call suite in my project, but I'll want to ignore the 'test' and just call from terminal
gradle test --tests TC1001 or gradle test -Dtest.single=TC1001
and this 2 options give the error
* What went wrong:
Execution failed for task ':test'.
No tests found for given includes: [com.automation.navigateSuite.TC1001]
the directory hierarchy is
src/test/java/com.automation/navigateSuite/TC1001.java

Related

Could not determine the dependencies of task -testone

I started learning Gradle (Java + Gradle) and created this very basic - build.gralde - file.
task testone(type: Test) {
println ("Started TestSetUp")
}
In Console when ran command -> gradlew testone -- intellij is throwing error:
> Configure project :
Started TestSetUp
FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':testone'.
I think i can help you with that , By changing the type from Test to Copy , this will build perfectly , Copy is a defined type in gradle and running gradle testone -q will show your output .
I think the problem is with your defined type , by declaring the type as Test you need to add more configuration for this , because the error i got when i tried to register the task like
tasks.register testone(type: Test) {
println ("Started TestSetUp")
}
was Could not find method testone() for arguments [{type=class org.gradle.api.tasks.testing.Test} so your issue is with the Test type , i spose your missing some extra configuration .
When you’re using a JVM language plugin — such as the Java Plugin —
you will automatically get the following:
A dedicated test source set for unit tests
A test task of type Test that runs those unit tests
In "build.gradle", after adding java plugin, the task ran successfully.
plugins {
id 'java'
}
task testone(type: Test) {
println ("Task of type Test Success")
}

Cross-module code coverage with Jacoco offline instrumentation in gradle mutlimodule project

I have to use Jacoco offline instrumentation in my project because there is PowerMock that is used as well.
The issue description: suppose you have gradle project with two modules: A, B. Module A has tests that cover a code from the module B. On code coverage data collection I figured out that coverage data(should be provided by the module A) for the module B is completely missed.
I've created a test project that demonstrates the issue: https://github.com/SurpSG/jacoco-offline-instrumentation
Jacoco offline instrumentation setup for gradle project is based on the answer https://stackoverflow.com/a/42238982/2689114
On the other hand, when I'm using jacoco gradle plugin I can observe that coverage data provided by module A for module B successfully collected to a summary report. I've created one more test project to demonstrate this: https://github.com/SurpSG/jacoco-gradle-plugin-merge-coverage
Am I have a wrong setup for the gradle multimodule project + jacoco offline instrumentation?
After some investigation, I figured out that modules dependencies in Gradle are resolved via .jar files:
<dependent-module>.classpath contains <dependency-module>.jar
So, in my case, I need to build some special jar that contains instrumented classes.
Instrumenting classes
task preprocessClassesForJacoco(dependsOn: ['classes']) {
ext.outputDir = buildDir.path + '/classes-instrumented'
doLast {
ant.taskdef(name: 'instrument',
classname: 'org.jacoco.ant.InstrumentTask',
classpath: configurations.jacoco.asPath)
ant.instrument(destdir: outputDir) {
fileset(dir: sourceSets.main.java.outputDir, includes: '**/*.class', erroronmissingdir: false)
}
}
}
The next step will be building instrumented jar:
task jacocoInstrumentedJar(type: Jar, dependsOn: [preprocessClassesForJacoco]) {
baseName "${project.name}-instrumented"
from preprocessClassesForJacoco.outputDir // path to instrumented classes
}
And finally, we need to replace the usual .jar with instrumented one
gradle.taskGraph.whenReady { graph ->
if (graph.hasTask(preprocessClassesForJacoco)) {
tasks.withType(Test) {
doFirst {
...
// getting a module dependencies
def modulesDependencies = moduleDependencies(project)
// removing regular jars
classpath -= files(modulesDependencies.jar.outputs.files)
// adding instrumented jars
classpath += files(modulesDependencies.jacocoInstrumentedJar.outputs.files)
}
}
}
}
I've updated the example project https://github.com/SurpSG/jacoco-offline-instrumentation with steps described above. Feel free to check out the project to try.

Gradle CreateDebugCoverageReport doesn't run local unit tests

I'm using jacoco for code coverage. It runs (./gradlew createDebugCoverageReport) fine and generates code coverage for all the androidTest cases. However, it doesn't run the local unit tests, and hence doesn't compute the code coverage by these tests. How can I achieve all test cases including local to run and code coverage for all. I'm not sure what I'm missing. Any pointers will be great.
I can successfully run all the local unit tests on JVM with ./gradlew testDebugUnitTest
Please let me know if any more information is required.
An updated answer for Android Studio Chipmunk and Gradle 7.3.3
This is in the project level gradle
buildscript {
dependencies {
classpath 'org.jacoco:org.jacoco.core:0.8.7'
}
}
These are in the module level gradle
plugins {
id 'jacoco'
}
android {
buildTypes {
debug {
testCoverageEnabled true
}
}
tasks.withType(Test) {
jacoco {
includeNoLocationClasses = true
excludes = ['jdk.internal.*']
}
}
}
And finally, the task that runs the tests.
task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest', 'createDebugCoverageReport']) {
reports {
xml.getRequired().set(true)
html.getRequired().set(true)
}
def fileFilter = [
'**/R.class',
'**/R$*.class',
'**/BuildConfig.*',
'**/Manifest*.*',
'**/*Test*.*',
'android/**/*.*'
]
def debugTree = fileTree(
dir: "$project.buildDir/tmp/kotlin-classes/debug",
excludes: fileFilter
)
def mainSrc = "$project.projectDir/src/main/java"
sourceDirectories.from(files([mainSrc]))
classDirectories.from(files([debugTree]))
executionData.from(fileTree(
dir: "$buildDir",
includes: [
"outputs/unit_test_code_coverage/debugUnitTest/testDebugUnitTest.exec",
"outputs/code_coverage/debugAndroidTest/connected/*/coverage.ec"
]
))
}
"$project.buildDir/tmp/kotlin-classes/debug" is for Kotlin. Change to "$project.buildDir/intermediates/classes/debug" for Java.
testDebugUnitTest runs unit tests and creates a coverage report at "outputs/unit_test_code_coverage/debugUnitTest/testDebugUnitTest.exec".
Note that path may differ. I searched for "exec" in the app folder to find it.
createDebugCoverageReport runs the Android tests and creates a coverage report at "outputs/code_coverage/debugAndroidTest/connected/*/coverage.ec". Note that this path may also differ. I searched for "coverage.ec" in the app folder to find it.
Finally, to run the tests and create a coverage report you can create a run configuration to run "clean jacocoTestReport" or tap ctrl twice in Android Studio and run "./gradlew clean jacocoTestReport" which will create the run configuration for you.
This helped. https://medium.com/#rafael_toledo/setting-up-an-unified-coverage-report-in-android-with-jacoco-robolectric-and-espresso-ffe239aaf3fa#.r2y0v7b5n
BIG SHOUT OUT FOR THE AUTHOR.

Gradle to execute Java class (without modifying build.gradle)

There is simple Eclipse plugin to run Gradle, that just uses command line way to launch gradle.
What is gradle analog for maven compile and run
mvn compile exec:java -Dexec.mainClass=example.Example
This way any project with gradle.build could be run.
UPDATE: There was similar question What is the gradle equivalent of maven's exec plugin for running Java apps? asked before, but solution suggested altering every project build.gradle
package runclass;
public class RunClass {
public static void main(String[] args) {
System.out.println("app is running!");
}
}
Then executing gradle run -DmainClass=runclass.RunClass
:run FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':run'.
> No main class specified
There is no direct equivalent to mvn exec:java in gradle, you need to either apply the application plugin or have a JavaExec task.
application plugin
Activate the plugin:
plugins {
id 'application'
...
}
Configure it as follows:
application {
mainClassName = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "NULL"
}
On the command line, write
$ gradle -PmainClass=Boo run
JavaExec task
Define a task, let's say execute:
task execute(type:JavaExec) {
main = project.hasProperty("mainClass") ? getProperty("mainClass") : "NULL"
classpath = sourceSets.main.runtimeClasspath
}
To run, write gradle -PmainClass=Boo execute. You get
$ gradle -PmainClass=Boo execute
:compileJava
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes
:execute
I am BOO!
mainClass is a property passed in dynamically at command line. classpath is set to pickup the latest classes.
If you do not pass in the mainClass property, both of the approaches fail as expected.
$ gradle execute
FAILURE: Build failed with an exception.
* Where:
Build file 'xxxx/build.gradle' line: 4
* What went wrong:
A problem occurred evaluating root project 'Foo'.
> Could not find property 'mainClass' on task ':execute'.
You just need to use the Gradle Application plugin:
apply plugin:'application'
mainClass = "org.gradle.sample.Main"
And then simply gradle run.
As Teresa points out, you can also configure mainClass as a system property and run with a command line argument.
Expanding on First Zero's answer, I'm guess you want something where you can also run gradle build without errors.
Both gradle build and gradle -PmainClass=foo runApp work with this:
task runApp(type:JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "package.MyDefaultMain"
}
where you set your default main class.
You can parameterise it and pass gradle clean build -Pprokey=goodbye
task choiceMyMainClass(type: JavaExec) {
group = "Execution"
description = "Run Option main class with JavaExecTask"
classpath = sourceSets.main.runtimeClasspath
if (project.hasProperty('prokey')){
if (prokey == 'hello'){
main = 'com.sam.home.HelloWorld'
}
else if (prokey == 'goodbye'){
main = 'com.sam.home.GoodBye'
}
} else {
println 'Invalid value is enterrd';
// println 'Invalid value is enterrd'+ project.prokey;
}

Gradle build without tests

I want to execute gradle build without executing the unit tests. I tried:
$ gradle -Dskip.tests build
That doesn't seem to do anything. Is there some other command I could use?
You should use the -x command line argument which excludes any task.
Try:
gradle build -x test
Update:
The link in Peter's comment changed. Here is the diagram from the Gradle user's guide
Try:
gradle assemble
To list all available tasks for your project, try:
gradle tasks
UPDATE:
This may not seem the most correct answer at first, but read carefully gradle tasks output or docs.
Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
You can add the following lines to build.gradle, **/* excludes all the tests.
test {
exclude '**/*'
}
The accepted answer is the correct one.
OTOH, the way I previously solved this was to add the following to all projects:
test.onlyIf { ! Boolean.getBoolean('skip.tests') }
Run the build with -Dskip.tests=true and all test tasks will be skipped.
Every action in gradle is a task, and so is test. And to exclude a task from gradle run, you can use the option --exclude-task or it's shorthand -x followed by the task name which needs to be excluded. Example:
gradle build -x test
The -x option should be repeated for all the tasks that needs to be excluded.
If you have different tasks for different type of tests in your build.gradle file, then you need to skip all those tasks that executes test. Say you have a task test which executes unit-tests and a task testFunctional which executes functional-tests. In this case, you can exclude all tests like below:
gradle build -x test -x testFunctional
Using -x test skip test execution but this also exclude test code compilation.
gradle build -x test
In our case, we have a CI/CD process where one goal is compilation and next goal is testing (Build -> Test).
So, for our first Build goal we wanted to ensure that the whole project compiles well. For this we have used:
./gradlew build testClasses -x test
On the next goal we simply execute tests:
./gradlew test
You can exclude tasks
gradle build --exclude-task test
https://docs.gradle.org/current/userguide/command_line_interface.html#sec:command_line_executing_tasks
the different way to disable test tasks in the project is:
tasks.withType(Test) {enabled = false}
this behavior needed sometimes if you want to disable tests in one of a project(or the group of projects).
This way working for the all kind of test task, not just a java 'tests'. Also, this way is safe. Here's what I mean
let's say: you have a set of projects in different languages:
if we try to add this kind of record in main build.gradle:
subprojects{
.......
tests.enabled=false
.......
}
we will fail in a project when if we have no task called tests
Reference
To exclude any task from gradle use -x command-line option. See the below example
task compile << {
println 'task compile'
}
task compileTest(dependsOn: compile) << {
println 'compile test'
}
task runningTest(dependsOn: compileTest) << {
println 'running test'
}
task dist(dependsOn:[runningTest, compileTest, compile]) << {
println 'running distribution job'
}
Output of: gradle -q dist -x runningTest
task compile
compile test
running distribution job
Hope this would give you the basic
In The Java Plugin:
$ gradle tasks
Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
testClasses - Assembles test classes.
Verification tasks
------------------
test - Runs the unit tests.
Gradle build without test you have two options:
$ gradle assemble
$ gradle build -x test
but if you want compile test:
$ gradle assemble testClasses
$ gradle testClasses
Please try this:
gradlew -DskipTests=true build

Categories

Resources