My project uses gradle and JUnit 5.01. The JUnit assertions are working fine. However, my regular Java assertions in the tested code itself are not firing. I would expect a failed assert to throw an AssertionError that would be caught and reported by JUnit.
I found this: How to disable assert in gradle test, and so created this build.gradle:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.2'
}
}
apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'maven'
apply plugin: 'org.junit.platform.gradle.plugin'
compileJava {
options.compilerArgs += "-Xlint:unchecked"
}
tasks.withType(Test) {
enableAssertions = true
}
repositories {
mavenCentral()
}
dependencies {
testCompile('org.junit.jupiter:junit-jupiter-api:5.0.1')
testCompile('org.apiguardian:apiguardian-api:1.0.0')
testRuntime('org.junit.jupiter:junit-jupiter-engine:5.0.1')
}
// Define the main class for the application
mainClassName = 'CMS'
jar {
manifest {
attributes 'Implementation-Title': 'CMS',
'Main-Class': 'com.brandli.cms.CMS'
}
}
junitPlatform {
filters {
includeClassNamePattern '.*'
}
}
test {
testLogging {
exceptionFormat = 'full'
}
}
What am I doing wrong?
Digging into gradle, and a lot of experimenting, led me to find that replacing
tasks.withType(Test) {
enableAssertions = true
}
with
junitPlatformTest {
enableAssertions = true
}
did the trick. I don't know why.
Related
I just made an update from spring boot version "2.2.1.RELEASE" to 2.5.6 and along with that I also updated the gradle version to 7.0. Before the update everything worked fine but after the update it seems that the bootRun task doesn't find the main class.
This is the error received:
Deprecated Gradle features were used in this build, making it
incompatible with Gradle 8.0. Use '--warning-mode all' to show the
individual deprecation warnings. See
https://docs.gradle.org/7.0/userguide/command_line_interface.html#sec:command_line_warnings
12 actionable tasks: 12 executed
Error: Could not find or load main class com.test.TestApplication
FAILURE: Build failed with an exception.
I ve followed the documentation https://docs.spring.io/spring-boot/docs/current/gradle-plugin/reference/htmlsingle/#running-your-application and I have the following build.gradle
buildscript {
ext {
springBootVersion = '2.5.6'
}
repositories {
// ..
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath "org.springframework.boot:spring-boot-starter-jersey:${springBootVersion}"
classpath("net.ltgt.gradle:gradle-apt-plugin:0.15")
classpath 'gradle.plugin.com.palantir.gradle.gitversion:gradle-git-version:0.11.0'
}
}
apply plugin: "java"
apply plugin: "war"
apply plugin: 'eclipse'
apply plugin: "idea"
apply plugin: "org.sonarqube"
apply plugin: "jacoco"
apply plugin: "maven-publish"
apply plugin: "net.ltgt.apt"
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'com.palantir.git-version'
def mapStructVersion = "1.3.0.Final"
def swaggerVersion = "1.6.3"
def junitVersion = "4.13.2"
sourceCompatibility = 1.8
sourceSets {
main {
java {
srcDir "${buildDir.absolutePath}/generated/source/apt/main"
}
}
test {
java {
srcDir "${buildDir.absolutePath}/generated/source/apt/main"
}
}
}
configurations.all {
resolutionStrategy.cacheChangingModulesFor 0, "seconds"
}
repositories {
// ...
}
task preBuild {
delete "${buildDir.absolutePath}/generated/source/apt/main"
}
build.dependsOn preBuild
configurations {
developmentOnly.extendsFrom compile
runtimeClasspath {
extendsFrom developmentOnly
}
}
/**
* Fix extension/file too long issue under windows
*/
task pathingJar(type: Jar) {
dependsOn configurations.developmentOnly
archiveAppendix = 'pathing'
doFirst {
manifest {
attributes "Class-Path": configurations.developmentOnly.files.collect {
it.toURI().toString().replaceFirst(/file:\/+/, '/')
}.join(' ')
}
}
}
/**
* With gradle 7, a duplicate strategy must be set in order to not encountering error during copy operation.
* Solution: EXCLUDE strategy do not allow duplicates by ignoring subsequent items to be created at the same path.
*/
processIntegrationTestResources {
duplicatesStrategy(DuplicatesStrategy.EXCLUDE)
}
bootRun {
main = 'com.test.TestApplication'
dependsOn pathingJar
doFirst {
classpath = files(sourceSets.main.output.files, pathingJar.archiveFile)
}
def debugPort = project.properties["${project.name}.debugPort"]
if (debugPort) {
jvmArgs = ["-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=${debugPort}"]
}
if (System.getProperty("LOG_PATH") == null) {
System.setProperty("LOG_PATH", project.projectDir.getCanonicalPath() + "/log")
}
if (System.getProperty("spring.profiles.active") == null) {
System.setProperty("spring.profiles.active", "some-profile")
}
if (System.getProperty("servicelayer.rrLogHumanReadable") == null) {
System.setProperty("servicelayer.rrLogHumanReadable", "true")
}
systemProperties = System.properties
}
def compileDependencies = [
"org.springframework.cloud:spring-cloud-starter-bootstrap:3.0.4",
"org.springframework.boot:spring-boot-starter-web",
"org.springframework.boot:spring-boot-starter-jersey",
"org.springframework.boot:spring-boot-starter-security",
"org.springframework.boot:spring-boot-starter-actuator",
"org.springframework.boot:spring-boot-starter-data-jpa",
"org.springframework.boot:spring-boot-starter-cache",
"io.swagger:swagger-jersey2-jaxrs:${swaggerVersion}",
"io.jsonwebtoken:jjwt:0.9.0",
"org.bitbucket.b_c:jose4j:0.6.3",
'org.flywaydb:flyway-core',
"org.mapstruct:mapstruct-jdk8:${mapStructVersion}",
"com.github.ben-manes.caffeine:caffeine",
'org.bouncycastle:bcprov-jdk15on:1.60'
]
// defined some dependencies. Not relevant
dependencies {
implementation compileDependencies
providedRuntime providedRuntimeDependencies
testImplementation testCompileDependencies
}
I tried both ways, from command line and from ide (IntelliJ)
clean bootRun -Dspring.profiles.active="some-profile"
I found the solution and the issue has been inside the task pathingJar.
Before:
task pathingJar(type: Jar) {
dependsOn configurations.developmentOnly
archiveAppendix = 'pathing'
doFirst {
manifest {
attributes "Class-Path": configurations.developmentOnly.files.collect {
it.toURI().toString().replaceFirst(/file:\/+/, '/')
}.join(' ')
}
}
}
After:
task pathingJar(type: Jar) {
dependsOn configurations.runtimeClasspath
archiveAppendix = 'pathing'
doFirst {
manifest {
attributes "Class-Path": configurations.runtimeClasspath.files.collect {
it.toURI().toString().replaceFirst(/file:\/+/, '/')
}.join(' ')
}
}
}
So the solution has been to change the following two lines of code
dependsOn configurations.developmentOnly -> dependsOn configurations.runtimeClasspath
attributes "Class-Path": configurations.developmentOnly.files.collect {...} -> attributes "Class-Path": configurations.runtimeClasspath.files.collect {...}
Long story short is that somehow another tasks interfered with this task on developmentOnly scope and I had to change it to runtimeClasspah
Edit:
Another issue might be inside of bootRun task. You can define the package where is the main class.
bootRun {
main = 'edu.somepacke.MyMainClass'
dependsOn pathingJar
doFirst {
classpath = files(sourceSets.main.output.files, pathingJar.archiveFile)
}
//extra logic
}
I am getting an error "File can't be indexed twice" in gradle build for sonar. Do i have to add any inclusion/exclusion property for sonar? Any help greatly appreciated.
If I take out "src/main/java" in test under sourceSets, I am getting compilation error for junit test cases.
This is how my build.gradle file content look,
group = 'groupid'
apply plugin: 'gradleFortify'
apply plugin: 'org.sonarqube'
apply plugin: 'eclipse'
apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: 'jacoco'
apply plugin: 'groovy'
//apply plugin: "java-library-distribution"
//apply plugin: 'distribution'
version=version
sourceCompatibility = 1.8
repositories {
maven {
url "artifactory"
credentials {
}
}
sonarqube {
properties {
property 'sonar.sourceEncoding', 'UTF-8'
property "sonar.exclusions", ["**/*Test.java"]
}
}
}
buildscript {
repositories {
maven {
url "artifactory"
credentials {
}
}
dependencies {
classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:4.9.7'
classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:3.0'
}
}
sourceSets {
main {
java {
srcDirs = ['src/main/java']
}
}
test {
java.srcDirs = ['src/test/java','src/main/java']
}
}
dependencies{
}
task preclean(type: Delete) {
delete 'build'
}
task jcompile(type: JavaCompile) {
dependsOn preclean
source = fileTree(dir: 'src/main/java', include: '**/*.java')
destinationDir = file('build/classes')
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
classpath = configurations.runtime
}
task copyResources( type: Copy ) {
}
task copyClasses( type: Copy ) {
}
jar {
dependsOn jcompile
archiveName = 'prj1.jar'
manifest {
attributes('Implementation-Title': project.name,
'Implementation-Version': project.version)
}
into('lib') {
println "includeInJar: " + configurations.runtime.collect { File file -> file }
from configurations.runtime
}
}
// jar.finalizedBy(jarTask) { }
sonarqube {
properties {
property "sonar.projectName", "prj-${version}"
property "sonar.projectKey", "prj-${version}"
}
}
test {
useJUnitPlatform()
finalizedBy jacocoTestReport
}
jacocoTestReport {
afterEvaluate {
classDirectories = files(classDirectories.files.collect {
fileTree(dir: it, includes: ['com/**'])
})
}
}
The issue described is most likely caused by custom tasks for what Gradle offers out of the box:
Task preclean deletes probably too much. Use clean instead.
Task jcompile compiles the main Java sources which basically duplicates compileJava. The jar task, by default, already depends on compileJava.
I suggest the following:
Remove sourceSets configuration since you're following the convention of using src/main/java and src/test/java.
Remove custom tasks preclean and jcompile.
Cleanup your build script and remove empty tasks copyClasses and copyResources as well as no-op assignment version=version.
From there on, should you have requirements to customize the build, try to resort to what Gradle offers already. You may want to read Building Java & JVM projects first.
I am incorporating null away and error prone into my app and have added the following to my top-level build.gradle
buildscript {
repositories {
google()
maven { url 'https://plugins.gradle.org/m2/' }
...
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.2'
classpath "net.ltgt.gradle:gradle-errorprone-plugin:0.0.16"
}
}
subprojects {
apply from: rootProject.file("gradle/nullaway.gradle")
}
...
then in the nullaway.gradle file I have
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
}
apply plugin: 'net.ltgt.errorprone'
if (this.name == 'javalib1' || this.name == 'javalib2') {
apply plugin: 'java-library'
dependencies {
annotationProcessor deps.thirdparty.nullaway
errorprone deps.thirdparty.error_prone
}
} else {
if (this.name == 'app') {
apply plugin: 'com.android.application'
} else {
apply plugin: 'com.android.library'
}
dependencies {
annotationProcessor deps.thirdparty.nullaway
errorprone deps.thirdparty.error_prone
}
}
tasks.withType(JavaCompile) {
if (!name.toLowerCase().contains("test")) {
options.compilerArgs += [
"-Xep:NullAway:WARN",
"-XepOpt:NullAway:AnnotatedPackages=com.mypackage",
"-Xep:RestrictTo:WARN",
"-XepExcludedPaths:.*/build/generated/.*"]
}
}
With this setup whenever I try to build my app I get an exception
Caused by: java.lang.IllegalAccessError: tried to access class com.google.common.graph.BaseGraph from class com.google.common.graph.Traverser
at com.google.common.graph.Traverser.forTree(Traverser.java:134)
at dagger.internal.codegen.ValidationReport.<clinit>(ValidationReport.java:63)
at dagger.internal.codegen.InjectValidator.validateMembersInjectionType(InjectValidator.java:257)
at dagger.internal.codegen.InjectBindingRegistryImpl.tryRegisterMembersInjectedType(InjectBindingRegistryImpl.java:269)
at dagger.internal.codegen.InjectBindingRegistryImpl.tryRegisterMembersInjectedType(InjectBindingRegistryImpl.java:253)
at dagger.internal.codegen.InjectProcessingStep$1.visitVariableAsField(InjectProcessingStep.java:67)
at dagger.internal.codegen.InjectProcessingStep$1.visitVariableAsField(InjectProcessingStep.java:57)
at com.sun.tools.javac.code.Symbol$VarSymbol.accept(Symbol.java:1550)
at dagger.internal.codegen.InjectProcessingStep.process(InjectProcessingStep.java:56)
at dagger.shaded.auto.common.BasicAnnotationProcessor.process(BasicAnnotationProcessor.java:330)
at dagger.shaded.auto.common.BasicAnnotationProcessor.process(BasicAnnotationProcessor.java:181)
I check the notes and I am using dagger version 2.16 and as you can see I have the exclude for build/generated files. What am I missing?
I'm using Spring Boot with Gradle.
Upgrading to the following:
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.0.RC1")
. . . from 1.2.7.RELEASE causes the following problem:
* What went wrong:
A problem occurred evaluating root project 'vampr'.
> Could not find property 'run' on org.gradle.testing.jacoco.plugins.JacocoPluginExtension_Decorated#12e13f2b.
How to fix this?
Build file:
buildscript {
ext.kotlin_version = '1.0.0-beta-1038'
repositories {
maven { url "https://repo.spring.io/libs-milestone" }
maven { url "https://repo.spring.io/libs-release" }
mavenLocal()
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.7.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'kotlin'
apply plugin: 'spring-boot'
apply plugin: "jacoco"
jar {
baseName = 'vampr'
version = '0.1.0'
}
repositories {
mavenLocal()
mavenCentral()
maven { url "https://repo.spring.io/libs-milestone" }
maven { url "https://repo.spring.io/libs-release" }
}
// New entire sourceSets
sourceSets {
main {
kotlin {
srcDir "src/main/kotlin"
}
}
test {
kotlin {
srcDir "test/main/kotlin"
}
}
integrationTest {
kotlin {
compileClasspath += main.output + test.output
runtimeClasspath += main.output + test.output
srcDir file('src/integration-test/kotlin')
}
resources.srcDir file('src/integration-test/resources')
}
main.java.srcDirs += 'src/main/kotlin'
}
configurations {
integrationTestCompile.extendsFrom testCompile
integrationTestRuntime.extendsFrom testRuntime
}
dependencies {
compile("org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version")
compile("org.springframework.boot:spring-boot-starter-data-rest")
// compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.social:spring-social-facebook:2.0.2.RELEASE")
testCompile("junit:junit")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
task wrapper(type: Wrapper) {
gradleVersion = '1.11'
}
task integrationTest(type: Test) {
testClassesDir = sourceSets.integrationTest.output.classesDir
classpath = sourceSets.integrationTest.runtimeClasspath
}
check.dependsOn integrationTest
integrationTest.mustRunAfter test
tasks.withType(Test) {
reports.html.destination = file("${reporting.baseDir}/${name}")
}
jacocoTestReport {
reports {
xml.enabled true
csv.enabled false
html.destination "${buildDir}/reports/coverage"
}
}
test {
jacoco {
append = true
destinationFile = file("$buildDir/jacoco/jacocoTest.exec")
classDumpFile = file("$buildDir/jacoco/classpathdumps")
}
}
jacoco {
applyTo run
}
task applicationCodeCoverageReport(type:JacocoReport){
executionData run
sourceSets sourceSets.main
}
It looks like ver 1.3.0+ replaces the "run" attribute with "bootRun".
Try updating
jacoco {
applyTo run
}
to
jacoco {
applyTo bootRun
}
I am trying to setUp my first gradle project with android studio:
I am getting the following error, which does not make any sense to me since 'app/src/main/AndroidManifest.xml' is a string.
Error:(23, 0) No signature of method:
org.gradle.api.java.archives.internal.DefaultManifest.srcFile() is
applicable for argument types: (java.lang.String) values:
[app/src/main/AndroidManifest.xml]
The gradle build script looks like this:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.9.2'
classpath 'org.robolectric.gradle:gradle-android-test-plugin:0.9.4'
classpath "org.mockito:mockito-core:1.9.5"
}
}
apply plugin: 'android'
allprojects {
repositories {
mavenCentral()
}
}
sourceSets {
main {
manifest.srcFile("app/src/main/AndroidManifest.xml")
}
unitTest {
java.srcDir file('src/test/java')
resources.srcDir file('src/test/res')
}
}
configurations {
unitTestCompile.extendsFrom runtime
unitTestRuntime.extendsFrom unitTestCompile
}
dependencies {
repositories {
mavenCentral()
}
unitTestCompile files("$project.buildDir/classes/release")
unitTestCompile 'junit:junit:4.10'
unitTestCompile 'org.robolectric:robolectric:2.1.+'
unitTestCompile 'com.google.android:android:4.0.1.2'
}
task unitTest(type:Test, dependsOn: assemble) {
testClassesDir = project.sourceSets.unitTest.output.classesDir
classpath = project.sourceSets.unitTest.runtimeClasspath
}
android {
compileSdkVersion 19
buildToolsVersion "19.0.0"
}
check.dependsOn unitTest
Thanks for any help.
Torsten
The error message means that either there is no method named srcFile on sourceSets.main.manifest, or it doesn't accept a string as argument. (Often it's the former.) I think that what you are trying to configure here is android { sourceSets { ... } }, not sourceSets { ... }.