Problems with testing in project with gradle - java

I want to use junt 4 for testing in my project, i added new class and one method to it for testing, when i try to tun it, i have this problem, how should i fix it.
When i try to run test i have a problem:
Could not write standard input to Gradle Test Executor 6.
java.io.IOException:
at java.base/java.io.FileOutputStream.writeBytes(Native Method)
at java.base/java.io.FileOutputStream.write(FileOutputStream.java:354)
at java.base/java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:81)
at java.base/java.io.BufferedOutputStream.flush(BufferedOutputStream.java:142)
at org.gradle.process.internal.streams.ExecOutputHandleRunner.forwardContent(ExecOutputHandleRunner.java:67)
at org.gradle.process.internal.streams.ExecOutputHandleRunner.run(ExecOutputHandleRunner.java:52)
at
...
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':test'.
> No tests found for given includes: [SimpleTest.test](filter.includeTestsMatching)
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 0s
5 actionable tasks: 2 executed, 3 up-to-date
My build.gradle file:
plugins {
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.8'
id 'org.beryx.jlink' version '2.12.0'
}
sourceCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
}
javafx {
version = "14"
modules = [ 'javafx.controls', 'javafx.fxml' ]
}
mainClassName = "$moduleName/org.openjfx.MainApp"
jlink {
options = ['--strip-debug', '--compress', '2', '--no-header-files', '--no-man-pages'] ;
launcher {
name = 'hellofx'
}
}
I don't now how to fix it, please help me!
Class with tests:
import org.junit.Assert;
import org.junit.Test;
public class SimpleTest {
#Test
public void test() {
Assert.assertTrue(true);
}
}
Also my projects repository

Try adding the following to your build.gradle. The problem is Gradle doesn't know how to find the tests as you haven't specified a test runner.
test {
useJUnit()
}

Related

Could not find method outputDir() on cucumber Java source of type org.gradle.api.internal.file.DefaultSourceDirectorySet

I am not able to run the cucumber task for the "com.github.samueltbrown.cucumber" plugin.
I get the following error:
FAILURE: Build failed with an exception.
* Where:
Build file '/Users/freid/app/build.gradle' line: 118
* What went wrong:
A problem occurred evaluating root project 'app'.
> Could not find method outputDir() for arguments [/Users/freid/app/src/cucumber/java] on cucumber Java source of type org.gradle.api.internal.file.DefaultSourceDirectorySet.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 0s
Here is my build.gradle file:
buildscript {
ext {
springBootVersion='2.2.4.RELEASE'
lombokVersion='1.18.4'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
plugins {
id 'org.springframework.boot' version '2.2.4.RELEASE'
id 'java'
id 'com.github.psxpaul.execfork' version '0.1.8'
id "com.jfrog.artifactory" version "4.7.2"
id "com.github.samueltbrown.cucumber" version "0.9"
}
dependencies {
testCompile 'info.cukes:cucumber-java:1.2.4'
}
sourceSets {
cucumber {
java {
compileClasspath += main.output + test.output
runtimeClasspath += main.output + test.output
srcDir file('src/cucumber/java')
}
resources.srcDir file('src/cucumber/resources')
}
}
cucumber {
formats = ['html:build/reports/html', 'json:build/reports/cucumber.json']
jvmOptions {
environment 'tag', System.getProperty("tag")
environment 'cucumber.local.server', 'localhost'
}
}
Given that the plugin com.github.samueltbrown.cucumber version 0.9 was released in 2015 and you are trying to run with a recent Spring Boot version, I would assume you are using a recent Gradle version as well.
So I believe you are hitting an incompatibility between the plugin and the Gradle version. Most likely an API changed and what the plugin does internally no longer works.
[/Users/freid/app/src/cucumber/java] looks like the toString of a collection of files, while SourceDirectorySet.outputDir only accepts a single File. So my guess is that the API of what returns the value that is used changed from a single file to a file collection at some point.

Azure Pipeline Gradle build fails for Spring

Im trying to build and deploy a Spring API on Azure via a Yaml pipeline. But i get an error during the spring application gradle build saying.
Error: /home/vsts/work/1/s/gradlew failed with return code: 1
Could not find org.springframework.boot:spring-data-rest-hal-browser:
Expanding the Error,
Starting a Gradle Daemon (subsequent builds will be faster)
> Task :compileJava FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Could not resolve all files for configuration ':compileClasspath'.
> Could not find org.springframework.boot:spring-data-rest-hal-browser:.
Required by:
project :
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 39s
1 actionable task: 1 executed
Error: /home/vsts/work/1/s/gradlew failed with return code: 1
at ChildProcess.<anonymous> (/home/vsts/work/_tasks/Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4/2.151.0/node_modules/vsts-task-lib/toolrunner.js:639:25)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:886:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
##[error]Error: /home/vsts/work/1/s/gradlew failed with return code: 1
##[section]Finishing: Gradle
Things i have tried.
I have tried changing specifying the versions of spring-data-rest-hal-browser in my project from.
compile("org.springframework.boot:spring-data-rest-hal-browser")
to
compile("org.springframework.boot:spring-data-rest-hal-browser:2.4.0.RELEASE")
and finally
compile("org.springframework.boot:spring-data-rest-hal-browser:3.0.8.RELEASE")
But still the same Error results
This is my current build.gradle file in my repo
plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.test.spring.api'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.11'
repositories {
mavenCentral()
}
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
developmentOnly("org.springframework.boot:spring-boot-devtools")
compile("org.springframework.boot:spring-boot-starter-data-rest")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-data-rest-hal-browser")
compile("org.springframework.data:spring-data-rest-webmvc:3.1.5.RELEASE")
}
And this is my current azure-pipelines.yml file
# Maven
# Build your Java project and run tests with Apache Maven.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/languages/java
trigger:
- master
pool:
vmImage: 'Ubuntu-16.04'
steps:
- task: Gradle#2
inputs:
workingDirectory: '$(system.defaultWorkingDirectory)'
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
javaHomeOption: 'JDKVersion'
jdkVersionOption: '1.8'
jdkArchitectureOption: 'x64'
publishJUnitResults: false
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
- task: CopyFiles#2
displayName: 'Copy Files to: Wireframe Directory on development server'
inputs:
SourceFolder: '$(Build.SourcesDirectory)'
TargetFolder: '$(Build.ArtifactStagingDirectory)'
- script:
cd '$(Build.ArtifactStagingDirectory)';
ls
- task: FtpUpload#1
displayName: 'FTP Upload: $(Build.ArtifactStagingDirectory)'
inputs:
credentialsOption: inputs
serverUrl: '[test server url]'
username: '[test username] '
password: '[test password] '
rootDirectory: '$(Build.ArtifactStagingDirectory)'
remoteDirectory: D:\home\site\wwwroot\webapps\ROOT\
preservePaths: true
I want to be able to automatically deploy my spring application to the server URL by pushing my code to it via the Azure devops pipeline which would build and deploy the spring application.
Thanks
So i resolved the issue by making some changes to the build.gradle file and build pipeline using help from the Microsoft Azure Repository for Intellij on Github: see here
My new build.gradle file looks like this:
plugins {
id 'org.jetbrains.intellij' version '0.4.1' apply false
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'java'
}
/**
*This is task for update Gradle wrapper version.
*/
task wrapper(type: Wrapper) {
gradleVersion = '4.7'
distributionUrl = "https://services.gradle.org/distributions/gradle-${gradleVersion}-all.zip"
}
apply plugin: 'io.spring.dependency-management'
group = 'com.test.spring.api'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
allprojects {
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
repositories {
mavenCentral()
}
}
task unitTest(type: Test) {
exclude '**/ApplicationTests/**'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
developmentOnly("org.springframework.boot:spring-boot-devtools")
compile("org.springframework.boot:spring-boot-starter-data-rest")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile group: 'org.springframework.data', name: 'spring-data-rest-hal-browser', version: '3.0.8.RELEASE'
compile("org.springframework.data:spring-data-rest-webmvc:3.1.5.RELEASE")
}
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
tasks.withType(FindBugs) {
ignoreFailures = true
reports {
html { enabled = true }
xml.enabled = !html.enabled
}
}
/**
* Preparing for release build
*/
task prepRelease() {
}
Also modified the azure-pipelines.yml file to include stacktrace and info to assist in debugging other gradle and build errors.
tasks: 'build --stacktrace --info'

ClassNotFound exception on ClassLoader.loadClass method when the class is in different module

I get ClassNotFound Exception in UserServiceApplication.kt file.
Below is my project structure.
Root Project
|
|---settings.gradle
|
|---common (library module) (Spring boot project)
| |
| |--build.gradle
| |--src/main/kotlin/com/simbalarry/common/util/StringValidator.kt
| |--src/main/kotlin/com/simbalarry/common/MainApp.kt
| |
|---user-manager (Spring boot project) (uses common)
| |--build.gradle
| |--src/main/kotlin/somepackage/UserServiceApplication.kt
Contents of all files
RootProject/settings.gradle
include ':common', ':user-manager'
rootProject.name = 'home-cuisine'
common/build.gradle
plugins {
id 'java-library'
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'org.jetbrains.kotlin.jvm' version '1.2.71'
id 'org.jetbrains.kotlin.plugin.spring' version '1.2.71'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.simbalarry'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
ext['kotlin.version'] = '1.2.71'
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-reflect'
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
}
compileKotlin {
kotlinOptions {
freeCompilerArgs = ['-Xjsr305=strict']
jvmTarget = '1.8'
}
}
common/com/simbalarry/common/util/StringValidator.kt
package com.simbalarry.common.util
class StringValidator {
fun hello(): String {
return "Bye"
}
}
common/com/simbalarry/common/MainApp.kt
package com.simbalarry.common
class MainApp
fun main(args: Array<String>) {
}
user-manager/build.gradle
plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'org.jetbrains.kotlin.jvm' version '1.2.71'
id 'org.jetbrains.kotlin.plugin.spring' version '1.2.71'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.simbalarry'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
test {
useJUnitPlatform()
}
repositories {
mavenCentral()
maven { url 'https://repo.spring.io/snapshot' }
maven { url 'https://repo.spring.io/milestone' }
}
dependencies {
implementation project(':common')
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.jetbrains.kotlin:kotlin-reflect'
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
}
compileKotlin {
kotlinOptions {
freeCompilerArgs = ['-Xjsr305=strict']
jvmTarget = '1.8'
}
}
user-manager/UserServiceApplication.kt
package com.simbalarry.usermanager
import com.simbalarry.common.util.StringValidator
class UserServiceApplication
fun main(args: Array<String>) {
println("Hieex")
val stringValidator = StringValidator()
}
When I do gradle bootRun on the user-manager package, I get the following exception
E:\Repos\HC7\user-manager>gradle bootRun
> Task :user-manager:bootRun FAILED
Hieex
Exception in thread "main" java.lang.NoClassDefFoundError: com/simbalarry/common/util/StringValidator
at com.simbalarry.usermanager.UserServiceApplicationKt.main(UserServiceApplication.kt:9)
Caused by: java.lang.ClassNotFoundException: com.simbalarry.common.util.StringValidator
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':user-manager:bootRun'.
> Process 'command 'C:\Program Files\Java\jdk1.8.0_181\bin\java.exe'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.2.1/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 4s
4 actionable tasks: 1 executed, 3 up-to-date
Can anyone guide me what is going wrong with this project. I had this problem in bigger project but I have pasted the narrowed down problem here.

RuntimeException: Sikulix fatal error: loadlib: opencv_java342.dll not in any libs folder

Project structure (full project can be downloaded here):
Launcher.java class:
import org.sikuli.script.Pattern;
public class Launcher {
public static void main(String[] args)
{
Pattern p1 = new Pattern(Launcher.class.getResource("sample.png"));
}
}
build.gradle file:
plugins {
id 'java'
}
group 'com.myproj'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
maven {
url "http://oss.sonatype.org/content/groups/public"
}
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile group: 'com.sikulix', name: 'sikulixapi', version: '1.1.4-SNAPSHOT'
}
Program throws following runtime error:
loadlib: opencv_java342.dll not in any libs folder
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.sikuli.script.Pattern.<init>(Pattern.java:125)
at Launcher.main(Launcher.java:7)
Caused by: java.lang.RuntimeException: Sikulix fatal error: loadlib: opencv_java342.dll not in any libs folder
at org.sikuli.script.Sikulix.terminate(Sikulix.java:58)
at org.sikuli.script.RunTime.terminate(RunTime.java:60)
at org.sikuli.script.RunTime.libsLoad(RunTime.java:915)
at org.sikuli.script.RunTime.loadLibrary(RunTime.java:1105)
at org.sikuli.script.Finder2.<clinit>(Finder2.java:33)
... 2 more
Disconnected from the target VM, address: '127.0.0.1:9172', transport: 'socket'
Process finished with exit code 1
Interesting thing is that my code worked in the morning smoothly. And when I got back home in the evening something went wrong. Can't run it anymore.. Thank you for any help!
What I've tried:
reload sikulixapi package using Gradle from scratch
download 3.4.2 opencv and load it in runtime like suggested here
add opencv_java342.dll directly to the project as described here
even tried to launch the project on different Windows machine to exclude environment issues - still fails
It happened, that there was a bug in the latest snapshot. Full conversation with developers can be found here.
So, in this situation you have at least two options:
Wait until developers fix the issue and introduce new snapshot. Bugs/questions can be reported here.
Tell gradle/maven to use previous stable version of sikulixapi
library. Full list of currently available snapshots can be found here. Gradle example:
dependencies {
compile group: 'com.sikulix', name: 'sikulixapi', version: '1.1.4-20181214.081346-62'
}

grgit NoClassDefFoundError

Gradle throws a NoClassDefFoundError when trying to execute a grgit task.
Start of build.gradle:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
classpath 'org.ajoberstar:gradle-git:1.2.0'
}
}
apply plugin: 'com.android.application'
//
//
import org.ajoberstar.grgit.*
task clone << {
File dir = new File('contrib/otherstuff')
if(!dir.exists()) {
def grgit = Grgit.clone(dir: dir, uri: 'https://github.com/someguy/otherstuff.git')
}
// TODO else (pull)
}
project.afterEvaluate {
preBuild.dependsOn clone
}
// rest omitted
Output:
Relying on packaging to define the extension of the main artifact has been deprecated and is scheduled to be removed in Gradle 2.0
:src:myproject:clone FAILED
FAILURE: Build failed with an exception.
* Where:
Build file '/home/me/src/myproject/build.gradle' line: 20
* What went wrong:
Execution failed for task ':src:myproject:clone'.
> java.lang.NoClassDefFoundError: org/codehaus/groovy/runtime/typehandling/ShortTypeHandling
* 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: 16.937 secs
Line 20 is the call to Grgit.clone().
Do I need to add groovy as a build dependency (which the error message seems to indicate)? How and where would I add it?
EDIT: gradle version is 1.10, if it matters.
As #user149408 pointed out the Gradle version (v1.10 vs v2.10) mismatch, I dug a little bit further:
gradle-git-plugin commit for v0.7.0 specifies the Gradle version used (v1.11), so the build with v1.10 works fine.
Because the Gradle plugin always built with compile localGroovy() and compile gradleApi() which comes from Gradle, then if it builds with Gradle 2.x, it would incur the Groovy mismatch error.
What went wrong: Execution failed for task ':src:myproject:clone'.
java.lang.NoClassDefFoundError: org/codehaus/groovy/runtime/typehandling/ShortTypeHandling
In fact, the combo of Gradle v2.10 and gradle-git v1.2.0 just works fine.
Some sample build.gradle similar structure as in the question.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.ajoberstar:gradle-git:1.2.0'
}
}
import org.ajoberstar.grgit.*
task clone << {
File dir = new File('contrib/gs-spring-boot')
if(!dir.exists()) {
def grgit = Grgit.clone(dir: dir, uri: 'https://github.com/chenrui333/gs-spring-boot.git')
}
// TODO else (pull)
}
./gradlew clone would give you:
$ ls contrib/gs-spring-boot/
CONTRIBUTING.adoc LICENSE.code.txt LICENSE.writing.txt README.adoc complete initial test
Hope it helps!
I’ve managed to solve it.
grgit-1.2.0 appears to depend on groovy. Adding a classpath entry for groovy in the buildscript/dependencies block resulted in a different error:
Relying on packaging to define the extension of the main artifact has been deprecated and is scheduled to be removed in Gradle 2.0
:src:myproject:clone FAILED
FAILURE: Build failed with an exception.
* Where:
Build file '/home/me/src/myproject/build.gradle' line: 23
* What went wrong:
Execution failed for task ':src:myproject:clone'.
> java.lang.IncompatibleClassChangeError: the number of constructors during runtime and compile time for org.ajoberstar.grgit.auth.AuthConfig$Option do not match. Expected -1 but got 2
* 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: 12.295 secs
Further research revealed that this might stem from a version incompatibility (as I’m stuck with Gradle 1.10 for other reasons).
Eventually I solved it by going back to grgit-0.7.0. Now my git task works and the repo gets cloned.

Categories