I am trying to migrate from Ant build to Gradle in my project. There are a bunch of test cases (subclasses of junit.framework.TestCase) and few test suites (subclasses of junit.framework.TestSuite). Gradle automatically picked up all test cases(subclasses of junit.framework.TestCase) to be run, but not the suites (subclasses of junit.framework.TestSuite).
I probably could work around by calling ant.junit to run it. But, I feel there should be a native easy way to force gradle to pick them and run. I couldn't find anything in the document . Am I missing something?
This was hard for me to figure out, but here is an example:
// excerpt from https://github.com/djangofan/WebDriverHandlingMultipleWindows
package webdriver.test;
import http.server.SiteServer;
import java.io.File;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
#RunWith(Suite.class)
#Suite.SuiteClasses({ TestHandleCacheOne.class, TestHandleCacheThree.class, TestHandleCacheThree.class })
public class SuiteOne extends MultiWindowUtils {
public static SiteServer fs;
#BeforeClass
public static void setUpSuiteOne() {
File httpRoot = new File("build/resources/test");
System.out.println("Server root directory is: " + httpRoot.getAbsolutePath() );
int httpPort = Integer.parseInt("8080");
try {
fs = new SiteServer( httpPort , httpRoot );
} catch (IOException e) {
e.printStackTrace();
}
initializeBrowser( "firefox" );
System.out.println("Finished setUpSuiteOne");
}
#AfterClass
public static void tearDownSuiteOne() {
closeAllBrowserWindows();
System.out.println("Finished tearDownSuiteOne");
}
}
And a build.gradle similar to this:
apply plugin: 'java'
apply plugin: 'eclipse'
group = 'test.multiwindow'
ext {
projTitle = 'Test MultiWindow'
projVersion = '1.0'
}
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '2.+'
compile group: 'junit', name: 'junit', version: '4.+'
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.+'
}
task testGroupOne(type: Test) {
//include '**/*SuiteOne.*'
include '**/SuiteOne.class'
reports.junitXml.destination = "$buildDir/test-results/SuiteOne")
reports.html.destination = "$buildDir/test-results/SuiteOne")
}
task testGroupTwo(type: Test) {
//include '**/*SuiteTwo.*'
include '**/SuiteTwo.class'
reports.junitXml.destination = "$buildDir/test-results/SuiteTwo")
reports.html.destination = "$buildDir/test-results/SuiteTwo")
}
Related
I am trying to build a jar with the following build.gradle:
plugins {
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.10'
}
application {
mainClass.set("edu.hm.dako.auditLogServer.AdminGuiStarter")
}
jar.enabled = true
javafx {
version = "18"
modules = ['javafx.controls', 'javafx.fxml']
}
sourceSets {
main {
resources {
srcDirs = ["src/main/java"]
includes = ["**/*.fxml"]
}
}
}
dependencies {
implementation project(':common')
implementation project(':communication')
implementation 'org.openjfx:javafx:18'
implementation group: 'org.apache.commons', name: 'commons-configuration2', version: '2.8.0'
implementation group: 'commons-beanutils', name: 'commons-beanutils', version: '1.9.4'
}
repositories {
mavenCentral()
}
jar {
manifest {
attributes "Main-Class": "edu.hm.dako.auditLogServer.AdminGuiStarter"
}
archiveBaseName = 'AdminGradle'
archiveVersion = '0.1.0'
}
The Main class of the project is following:
package edu.hm.dako.auditLogServer;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class AdminGuiStarter extends Application{
#Override
public void start(Stage stage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("AdminGui.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
} catch (IOException e) {
e.printStackTrace();
System.out.println(e);
}
}
// bitte über gradle starten, da sonst JavaFx Runtime components fehlen
public static void main(String[] args) {
launch();
}
}
When I then try to execute the jar, I get this error: java.lang.NoClassDefFoundError: javafx/application/Application
How can I fix this so that the jar will execute successful? When I run the Application via Gradle run, everything works fine.
My Minecraft Plugin doesn't load
I tried reinstalling Java
rebuilding the jar
and tried to remake the code
I used java 11
in IntelliJ Idea
and I used Minecraft 1.15.2
on MacOS 10.15.7
and I coded in Kotlin
Error Message:
org.bukkit.plugin.InvalidPluginException: Abnormal plugin type
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:80) ~[spigot-1.15.2.jar:git-Spigot-a99063f-be6aaf0]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:135) ~[spigot-1.15.2.jar:git-Spigot-a99063f-be6aaf0]
at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:394) ~[spigot-1.15.2.jar:git-Spigot-a99063f-be6aaf0]
at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:301) [spigot-1.15.2.jar:git-Spigot-a99063f-be6aaf0]
at org.bukkit.craftbukkit.v1_15_R1.CraftServer.loadPlugins(CraftServer.java:353) [spigot-1.15.2.jar:git-Spigot-a99063f-be6aaf0]
at net.minecraft.server.v1_15_R1.DedicatedServer.init(DedicatedServer.java:210) [spigot-1.15.2.jar:git-Spigot-a99063f-be6aaf0]
at net.minecraft.server.v1_15_R1.MinecraftServer.run(MinecraftServer.java:784) [spigot-1.15.2.jar:git-Spigot-a99063f-be6aaf0]
at java.lang.Thread.run(Thread.java:834) [?:?]
Caused by: java.lang.InstantiationException
at jdk.internal.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48) ~[?:?]
at java.lang.reflect.Constructor.newInstance(Constructor.java:490) ~[?:?]
at java.lang.Class.newInstance(Class.java:584) ~[?:?]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:76) ~[spigot-1.15.2.jar:git-Spigot-a99063f-be6aaf0]
... 7 more
My Main Class the only Class that the Project have (it is in Kotlin):
package main
import org.bukkit.Bukkit
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Entity
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.inventory.PlayerInventory
import org.bukkit.plugin.PluginManager
import org.bukkit.plugin.java.JavaPlugin
public abstract class Loader : JavaPlugin(), Listener, CommandExecutor{
override fun onEnable() {
Bukkit.broadcastMessage("Aura Plugin test by Woody1474747")
}
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if(sender is Player){
when(command.name){
"aura" -> {
val plinv:PlayerInventory = sender.getInventory()
val item1 = plinv.getItem(0)
val item8 = plinv.getItem(8)
sender.sendMessage(item1.toString())
}
}
}
return true
}
}
My plugin.yml
name: auraplugtest
version: 1.0.0
description: fsaf
main: main.Loader
commands:
aura:
usage: /<command>
My build.gradle:
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.3.61'
id 'com.github.johnrengelman.shadow' version '2.0.4'
}
group 'org.example'
version '1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
repositories {
maven {
url = 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/'
content {
includeGroup 'org.bukkit'
includeGroup 'org.spigotmc'
}
}
maven {
url = 'https://oss.sonatype.org/content/repositories/snapshots'
}
}
dependencies {
compileOnly 'org.bukkit:bukkit:1.14.4-R0.1-SNAPSHOT'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
testCompile group: 'junit', name: 'junit', version: '4.12'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
The answer is simple, your class cannot be abstract!
Fixed code:
// removed abstract keyword
public class Loader : JavaPlugin(), Listener, CommandExecutor {
// ...
}
I get an error in he "import org.springframework.data cannot be
resolved" in following code
package com.steinko.reactsprinboottutorial.RestfulWebService;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface TodoRepository extends CrudRepository<Todo, Long>{
List<Todo> findByName(String Name);
}
The gradle build.gradle looks like
plugins {
id 'org.springframework.boot' version '2.3.3.RELEASE'
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
}
apply plugin: 'java'
apply plugin: 'eclipse'
repositories {
mavenCentral()
jcenter()
mavenLocal()
// maven { url "http://dl.bintray.com/epam/reportportal" }
}
sourceCompatibility = '14'
sourceSets {
intTest {
compileClasspath += sourceSets.main.output
runtimeClasspath += sourceSets.main.output
}
}
configurations {
intTestImplementation.extendsFrom implementation
intTestCompile.extendsFrom testCompile
intTestRuntimeOnly.extendsFrom runtimeOnly
}
dependencies {
//implementation 'com.epam.reportportal:logger-java-log4j:5.0.2'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.modelmapper:modelmapper:2.3.8'
// https://mvnrepository.com/artifact/javax.validation/validation-api
compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'
implementation 'org.springframework.boot:spring-boot-starter-validation'
runtimeOnly 'org.postgresql:postgresql'
// https://mvnrepository.com/artifact/org.testcontainers/testcontainers
testCompile group: 'org.testcontainers', name: 'testcontainers', version: '1.15.0-rc1'
testCompile group: 'org.testcontainers', name: 'postgresql', version: '1.15.0-rc1'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.rest-assured:spring-mock-mvc:4.3.1'
testImplementation 'io.rest-assured:rest-assured-common:4.3.1'
testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa'
testCompile group: 'org.modelmapper', name: 'modelmapper', version: '2.3.8'
testImplementation 'com.epam.reportportal:agent-java-junit5:5.0.0-RC-1'
intTestCompile group: 'org.testcontainers', name: 'testcontainers', version: '1.15.0-rc1'
intTestCompile group: 'org.testcontainers', name: 'postgresql', version: '1.15.0-rc1'
intTestImplementation 'org.springframework.boot:spring-boot-starter-test'
intTestImplementation 'io.rest-assured:spring-mock-mvc:4.1.2'
intTestImplementation 'com.epam.reportportal:agent-java-junit5:5.0.0-RC-1'
intTestRuntimeOnly 'org.postgresql:postgresql'
}
test {
// testLogging.showStandardStreams = true
useJUnitPlatform()
// systemProperty 'junit.jupiter.extensions.autodetection.enabled', true
}
task integrationTest(type: Test) {
description = 'Runs integration tests.'
group = 'verification'
testClassesDirs = sourceSets.intTest.output.classesDirs
classpath = sourceSets.intTest.runtimeClasspath
shouldRunAfter test
}
When I run the test for the service I get a nullpointer for repository
TodoServiceTest > shoulCreateTodo() FAILED
java.lang.NullPointerException at TodoServiceTest.java:55
TodoServiceTest > shouldDeleteTodo() FAILED
java.lang.NullPointerException at TodoServiceTest.java:48
package com.steinko.reactsprinboottutorial.RestfulWebService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Disabled;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class TodoServiceTest {
private static final Logger logger = LoggerFactory.getLogger(TodoServiceTest.class);
private TodoService service = new TodoService();
#Test
void ShouldExist() {
assertNotNull (service);
}
#Test
void shouldDeleteTodo() {
service.deleteTodo("stein", 1L);
}
#Test
void shoulCreateTodo() {
Date date = DateFactory.generetDate("01-01-2020 12:00:00");
TodoDto todo = new TodoDto(1,"Stein","Fix Kjakk", date,false);
service.createTodo(todo);
}
}
The service test looks like
package com.steinko.reactsprinboottutorial.RestfulWebService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#Service
public class TodoService {
private static final Logger logger = LoggerFactory.getLogger(TodoService.class);
#Autowired
private TodoRepository repository;
public List<TodoDto> getTodos(String name) {
List<Todo> todos = repository.findByName(name);
TodoConverter converter = new TodoConverter();
List<TodoDto> dtos = converter.convertToDtos(todos);
return dtos;
}
public void deleteTodo(String name, Long id) {
repository.deleteById(id);
}
public void createTodo(TodoDto dto) {
TodoConverter converter = new TodoConverter();
Todo todo = converter.convertToEntity(dto);
validateEntity(todo);
repository.save(todo);
}
private void validateEntity(Todo todo) {
List<String> errorMessage = new ArrayList<>();
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Todo>> constraintViolations = validator.validate(todo);
for (ConstraintViolation<Todo> constraintViolation : constraintViolations) {
errorMessage.add(constraintViolation.getMessage());
}
if (errorMessage.size() > 0) {
throw new ConstraintViolationException(constraintViolations);
}
}
}
How do I get access to org.springframework.data and an object at repository variabel ?
You have to annotate the test class with either #SpringBootTest or #DataJpaTest so the repository will be initialised and injected into your service. Furthermore, you have to autowire your service in the test, or the repository will not be injected in the instance created by you.
I am using the firebase admin SDK with IntelliJ whenever I try to run this code I got this error message:
Error:(15, 50) java: cannot access com.google.auth.Credentials
class file for com.google.auth.Credentials not found
this is the code:
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import java.io.FileInputStream;
import java.io.IOException;
public class main {
public static void main (String args[]) throws IOException {
FileInputStream serviceAccount =
new FileInputStream("C:/Users/fusion/Desktop/projects/aesf/google-services.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://myDataBaseName.firebaseio.com")
.build();
FirebaseApp.initializeApp(options);
}
}
And this is the gradle file:
plugins {
id 'java'
}
version '1.0-SNAPSHOT'
apply plugin: 'java'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
implementation 'com.google.firebase:firebase-admin:6.6.0'
implementation 'com.google.auth:google-auth-library-oauth2-http:0.12.0'
}
gradle :
rootProject.name = 'aesf'
Check you are using one of these
remove them
google-oauth-client-1.22.0.jar
google-oauth-client-appengine-1.22.0.jar
google-oauth-client-servlet-1.22.0.jar
also update your classpath
classpath 'com.google.gms:google-services:4.2.0'
I am running a gradle project and I an trying to have log4j both log to the console as well as to a file. While the error is logged to the console, no file is logged to. I have my log4j.properties in the src/main/resources. I have tried moving the properties files to the src folder as well as to just about every folder suggested on SO without success. I have tried both rollingFile and File within the log4j as well. Is there something wrong with by log4j.properties file, or am I not placing the file in the correct spot?
Here are my current files
log4j.properties
# root level configurations
log4j.rootLogger=INFO,console,rollingFile
# configuration for console outputs
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# configuration for file output (into a file named messages.log)
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.File=/home/cbolles/devel/testing/gradle_testing/messages.log
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
build.gradle
apply plugin: 'java'
repositories {
jcenter()
}
dependencies {
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.8.2'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.8.2'
compile 'org.slf4j:slf4j-log4j12:1.7.18'
testCompile 'junit:junit:4.12'
}
task(runSimple, dependsOn: 'classes', type: JavaExec) {
main = 'com.bolles.ErrorTester'
classpath = sourceSets.main.runtimeClasspath
args 'mrhaki'
systemProperty 'simple.message', 'Hello '
}
defaultTasks 'runSimple'
LogTesting.java
package com.bolles;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LogTesting
{
private static final Logger log = LogManager.getLogger(LogTesting.class);
public static void reportError(Exception e, boolean consoleLog)
{
String errorMessage = "";
if(e.getMessage() != null)
{
errorMessage = e.getMessage();
}
StringWriter stackTraceWriter = new StringWriter();
e.printStackTrace( new PrintWriter(stackTraceWriter));
String stackTrace = stackTraceWriter.toString();
log.error(errorMessage);
log.log(Level.ERROR, errorMessage + "\n" + stackTrace);
}
}
ErrorTester.java
package com.bolles;
public class ErrorTester
{
public static void nullStringTest()
{
String errorString = null;
try
{
System.out.print(errorString);
}
catch(Exception e)
{
LogTesting.reportError(e, true);
}
}
public static void main(String[] args)
{
nullStringTest();
}
}
None of the other answers seem to work for my issue.
The apparent problem seems to be that you are using log4j's LogManager and Logger classes. Make the following changes to your LogTesting class (slf4j is already among your dependencies as I see)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
...
private static final Logger log = LoggerFactory.getLogger(LogTesting.class);
...
log.error(errorMessage);
//log.log(Level.ERROR, errorMessage + "\n" + stackTrace); //no such method in slf4j
and it should write the error in the file too as expected.
(also you seem to need to modify the ErrorTester class because currently there is no exception thrown from there so LogTesting.reportError() is not called)