How to import the '#Test' method in Java - junit

I am trying to use the #Test function on a small program as I am directed to using Java 8 tutorial on youtube. Find it here.
I am up to lesson 2 which starts at 21:59.
Here is the youtube link.
https://www.youtube.com/watch?v=grEKMHGYyns
However, I have the following errors:
When trying to import the Test function the advice given by my Apache Netbeans IDE is ...
"package org.junit does not exist"
... the same happens for "org.Assert"
Over the "#Test" function on line 9 of my PersonTest.java file, the IDE gives the error...
"Cannot find symbol".
The same error exists over the "assertEquals" method on line 13.
Attempted Solution 1: Search dependency at Maven Repositories for org.junit.Test.
Result 1: "No matching items."
Attempted Solution 2: write the dependencies into the pom.xml file.
Result: n/a. Nothing happened.
My code on the PersonTest.java file:
package com.marcusbiel.javacourse.lesson2;
import org.junit.Test;
import org.Assert.assertEquals;
public class PersonTest {
#Test
public void shouldReturnHelloWorld() {
Person tristan = new Person();
assertEquals("Hello World",tristan.helloWorld() );
}
}
My code on the Person.java file:
package com.marcusbiel.javacourse.lesson2;
public class Person {
public String helloWorld(){
return "Hello World";
}
}
My code on the pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>mavenproject1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>12</maven.compiler.source>
<maven.compiler.target>12</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Note: I tried to fix the problem by adding in the...
"
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
... part. I don't think it's working. I have no feedback from the program on that note.
When I run it. I want to see a messaging saying "all tests passed". As in the video here... (I have a timestamp on this link where the outcome occurs).
youtu.be/grEKMHGYyns?t=2125

Problem is very old JUnit version 3.8.1 (from 2007) combined with code that requires JUnit 4.
Issue can be solved by using Junit 4:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
Also Assert.assertEquals import is wrong. Should be:
import static org.junit.Assert.assertEquals;

I think that you should clean up and update your project dependencies.
Perform a mvn clean install from netbeans IDE.
This will update your project dependencies. I think this will solve the issue of unresolvable dependencies.
Here is the doc to using maven with netbeans

Related

How do I connect Spring-MVC to a hosted website?

I recently signed up for a free website and the URL is http://kensinelli.infinityfreeapp.com. I'm trying to learn Spring MVC, and rather than do everything on localhost:8080, I wanted to do everything on an actual website so that potential employers can easily see whatever I decide to create. However, I've been struggling to figure out how to accomplish this. I've Google'd quite a bit and found some resources mentioning the application.properties file, and I've set server.address = http://kensinelli.infinityfreeapp.com and server.port = 80. I've also tried setting server.address = 185.27.134.151 which is the stated IP address in the website control panel. When I use the IP address and try to start Spring, I get the error:
org.springframework.context.ApplicationContextException: Failed to start bean 'webServerStartStop'; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat server
When I use http://kensinelli.infinityfreeapp.com instead of the IP address I get this error:
Failed to bind properties under 'server.address' to java.net.InetAddress:
Property: server.address
Value: http://kensinelli.infinityfreeapp.com
Origin: class path resource [application.properties] - 1:16
Reason: failed to convert java.lang.String to java.net.InetAddress
Action:
Update your application's configuration
So I think server.address is supposed to be an actual IP address and not a named server address that would be run through a DNS.
But do I even need to do this through Spring's built-in Tomcat? Can I circumnavigate that somehow or is Tomcat required even to connect to external websites?
My files are currently as such:
package spring.project;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class WebProjectApplication {
public static void main(String[] args) {
SpringApplication.run(WebProjectApplication.class, args);
System.out.println("Hello world");
}
}
pom.xml (some dependencies are commented out because I plan on using them in the future but they were causing me errors upon startup for now):
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>spring.project</groupId>
<artifactId>webProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>webProject</name>
<description>spring project</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<!-- <dependency> -->
<!-- <groupId>org.springframework.boot</groupId> -->
<!-- <artifactId>spring-boot-starter-jdbc</artifactId> -->
<!-- </dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.springframework.boot</groupId> -->
<!-- <artifactId>spring-boot-starter-thymeleaf</artifactId> -->
<!-- </dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.thymeleaf.extras</groupId> -->
<!-- <artifactId>thymeleaf-extras-springsecurity5</artifactId> -->
<!-- </dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.postgresql</groupId> -->
<!-- <artifactId>postgresql</artifactId> -->
<!-- <scope>runtime</scope> -->
<!-- </dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties:
server.address=185.27.134.151
server.port=80
I understand that my code isn't doing anything at this point, but I'm just trying to get it to start without errors right now. I'm really new at this so please don't assume I know much of anything. A step-by-step walkthrough would be hugely appreciated. Please don't just say "Read the documentation" because I've already looked at it and either I'm not finding what I'm looking for or not understanding it, so I need someone to clarify. Thank you.
The basic answer is you need to run the application on their server. You cant run it locally and have it serve requests to a different location. To this end you need to package your application, upload it to the remote server, configure the configuration for the remote server properly, and have the remote server execute your packaged application. You may find it is easier to use a service like Heroku instead. They have good tutorials and abstract away some of the complexity involved in managing deployments. https://devcenter.heroku.com/articles/deploying-spring-boot-apps-to-heroku

Error:org.apache.commons.logging.LogFactoryjava.lang.NoClassDefFoundError for application build with micronaut-bom1.2.10, graal19.2.1 & aws-sdk2.10.56

Created an application using micronaut bom 1.2.10 version, along with software.amazon.awssdk:lambda:2.10.56 & software.amazon.awssdk:s3:2.10.56 dependencies which had functionality to retrieve data from s3 storage and used graal 19.2.1 to create a native image.
The native image is successfully created but when i try to access the endpoint it fails for below exception:
failed: org.apache.commons.logging.LogFactoryjava.lang.NoClassDefFoundError: org.apache.commons.logging.LogFactory
and series of exceptions with specifically while creating S3 client.
The exception also had failure at below point:
failed: Could not initialize class software.amazon.awssdk.http.apache.internal.conn.SdkTlsSocketFactoryjava.lang.NoClassDefFoundError: Could not initialize class software.amazon.awssdk.http.apache.internal.conn.SdkTlsSocketFactory
Code for S3Client :
S3Client s3Client = S3Client.builder().region(getRegion()).build();
build-native-image.sh
${GRAALVM_HOME}/bin/native-image --no-server -cp example-function-*-all.jar
-H:IncludeResources="git.properties"
-H:IncludeResources="logback.xml"
-H:IncludeResources="application.properties" \
So this issue was resolved by adding below configuration in build.gradle:
allprojects {
configurations {
all {
exclude(group = "commons-logging")
}
}
}
and in the dependencies added:
compile group: 'org.slf4j', name: 'jcl-over-slf4j', version: '1.7.30'
I hope this helps.
I faced the same issue, when running tests, with the exact same NoClassDefFoundError but when using AWS sts and secretsmanager libraries. I could actually get it to work by just including the jcl-over-slf4j dependency, while the error happened when using the slf4j-api dependency. I did not need to exclude commons-logging. Snippet of dependency in maven pom.xml that worked:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>2.17.89</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>secretsmanager</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>sts</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</dependency>
</dependencies>

How to fix "Error: JavaFX runtime components are missing, and are required to run this application"

My JavaFx application is running perfectly well from source but When I'm compiling to a single jar file I get error :
Error: JavaFX runtime components are missing, and are required to run this application.
I'm using Maven as my repository manager and My install with Maven is sucessfull.
Note: In my Intellij build artifact I can see that Intellij include JavaFx and all its libraries
a) For my maven project the trick was to use an extra starter class that does not inherit from javafx.application.Application:
public class GUIStarter {
public static void main(final String[] args) {
GUI.main(args);
}
}
The JavaFx dependencies are included in my pom.xml as follows:
<!-- JavaFx -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-base</artifactId>
<version>12</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>12</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics </artifactId>
<version>12</version>
<classifier>win</classifier>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>12</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-web</artifactId>
<version>12</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-media</artifactId>
<version>12</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-swing</artifactId>
<version>12</version>
</dependency>
In order to include fxml files in your build, you might need to define them as resource:
!-- define JavaFx files as resources to include them in the jar -->
<resource>
<directory>${basedir}/src/main/java/foo/baa/view</directory>
<filtering>false</filtering>
<targetPath>foo/baa/view</targetPath>
</resource>
b) As an alternative, an extra maven plugin "javafx-maven-plugin" could be used to build the javafx appication, see example project at https://openjfx.io/openjfx-docs/#maven (This did not work for me. I have several pom files and want to reference the javafx dependencies in a sub project. My main class could not be found by the javafx-maven-plugin.)
In Java 11 the JavaFX components have been removed into their own SDK, so when you run it won't be able to find them in the runtime.
The JavaFX page has the instructions to get it going: https://openjfx.io/openjfx-docs/#install-javafx
In short, you have to compile / run by adding the javafx modules in, either as options passed on the command line, or using a modular project.
I found that the modular project with Maven and IntelliJ worked best for me. https://openjfx.io/openjfx-docs/#IDE-Intellij
In the modular method you have a module-info.java file that describes all the modules that your project "requires", and allows you to "open" them to other modules. If you have a bunch of Maven dependencies you have to add them in the requires list too though. (IntelliJ can make this easy - find the error about no requires in the code and alt-enter)
Once everything was working with modules etc, I had to make a Fat Jar using I think the Maven shade plugin, to put everything together. Then it would work running the jar from the command line.
However, after getting my Java 11 code ##$%## working after 2 days of pain, I went back to Java 8 (using correto SDK for latest version) as Java 11 doesn't have packaging and IntelliJ can't do it for you.

Emma code coverage with JUnit and Powermock

I am using JUnit with Powermockito mocking.
I have to work on a CLI environment with maven or ant.
emma version: ema-2.0.5312
powermock version: powermock-mockito-1.5.1-full
junit version: junit-4.9
When I run junit through the following command, everything works find:
java org.junit.runner.JUnitCore some.package.ClassTest
However, when I used emma to check the code coverage:
java emmarun -cp $CLASSPATH -report txt org.junit.runner.JUnitCore some.package.ClassTest
I got the following error:
1) initializationError(some.pakage.ClassTest)
java.lang.ClassCastException: org.powermock.modules.junit4.PowerMockRunner cannot be cast to org.junit.runner.Runner
Other test classes without using powermock work fine.
Does anyone have some suggestion to this? thanks in advance.
while using powermock, you can not find out the coverage using Emma
See this discussion on developer's side
You can use MockitoJunitRunner and specify a rule to use PowerMock since Eclemma works along with MockitoJUnitRunner.
Something like this:
#RunWith(MockitoJUnitRunner.class) // This supports Eclemma Plugin. Powermock doesn't.
#PrepareForTest({/* StaticClasses for Powermock here */})
public class ClassTest {
// These two statements; the static block and #Rule make sure Powermock works along with Mockito!!
static {
PowerMockAgent.initializeIfNeeded();
}
#Rule
public PowerMockRule powerMockRule = new PowerMockRule();
#Mock // To mock dependent class
private MockClass mock;
#InjectMocks //To Inject all mocks in this class
private ClassUnderTest classObject;
//Rest of the code here.
}
Dependencies needed:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-rule-agent</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency
Also you need to add this to the configurations under Coverage As -> Coverage Configurations -> Arguments.
Inside VM Arguments add -noverify and save.
for this to work with Jacoco use the following statement in your pom.xml .
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<argLine>${argLine} -noverify -javaagent:${settings.localRepository}/org/powermock/powermock-module-javaagent/1.6.2/powermock-module-javaagent-1.6.2.jar</argLine>
</configuration>
</plugin>

jetty-env.xml with DataSource leads to failing WebAppContext on mvn jetty:run

I have a really simple webapp project with maven and jetty that has been working very well until now. But now I need to setup MySQL connection pooling with JNDI as the database connections always time out.
First of all here is the relevant content of my pom.xml:
<modelVersion>4.0.0</modelVersion>
...
<packaging>war</packaging>
...
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jetty-version>8.1.0.v20120127</jetty-version>
</properties>
<dependencies>
...
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.20</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty-version}</version>
<type>maven-plugin</type>
</dependency>
</dependencies>
...
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty-version}</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
</configuration>
</plugin>
</plugins>
...
</build>
Now I created a jetty-env.xml in the folder /src/main/webapp/WEB-INF with the following content:
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<New id="project-db" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg>jdbc/db</Arg>
<Arg>
<New class="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource">
<Set name="url">jdbc:mysql://www.example.com:3306/mydb</Set>
<Set name="username">dbuser</Set>
<Set name="password">dbpass</Set>
</New>
</Arg>
</New>
</Configure>
But the problem is that I can't even test if this connection works as the jetty-maven-plugin fails to start on the goal
mvn jetty:run
with the following error:
WARN:oejw.WebAppContext:Failed startup of context o.m.j.p.JettyWebAppContext
{/,file:/D:/documents/programmierung/workspace/battleships-trunk/src/main/webapp/}
,file:/D:/documents/programmierung/workspace/battleships-trunk/src/main/webapp/
java.lang.IllegalArgumentException: Object of class
'org.mortbay.jetty.plugin.JettyWebAppContext' is not of type
'org.eclipse.jetty.webapp.WebAppContext'.
Object Class and type Class are from different loaders.
So how can I get this to work? I'm forced to use Jetty version 8.x as I need WebSocket support and as the remote productive server will be running Jetty 8.
EDIT
Before Pavel Veller's answer I tried the following: Deployed the assembled war to the remote jetty8 server and got the same error only that the previous error now reads as follows:
java.lang.IllegalArgumentException: Object of class
'org.eclipse.jetty.webapp.WebAppContext' is not of type
'org.eclipse.jetty.webapp.WebAppContext'.
Object Class and type Class are from different loaders.
So it seems as if there are multiple class loaders conflicting.
EDIT2
As requested by Pavel I recreated the error with a simplified webapp which you can find here on Dropbox. It is a zipped eclipse maven project.
Try removing the dependency on jetty-maven-plugin- this dependency adds the plugin to the WAR, which you don't want.
If you need to use any classes from Jetty itself, add a dependency for the specific version of Jetty (rather than the plugin) with a scope of provided.
It looks like it's pulling jetty 6 from somewhere. The exception you're seeing seems to be coming from the code that parses jetty-env.xml (org.mortbay.jetty.plus.webapp.EnvConfiguration). The XMLConfiguration class compares the class you declare on the Configure element with the actual class of what it gets from getWebAappContext(). The latter is instance of org.mortbay.jetty.plugin.JettyWebAppContext in your case and you expect it to be org.eclipse.jetty.webapp.WebAppContext (which would be the parent class for JettyWebAppContext had they both come from the same "namespace").
It's hard to tell where that would be happening from but maybe inspect your .m2 and confirm you have the proper binaries for your jetty dependencies? It has got to be running not the version you expect it to run.
UPDATE. Jetty does the following when it loads the classes defined in the configuration:
first load with Thread.currentThread().getContextClassLoader() and
loop through all getParent() until all options are exhausted.
if not successful, attempt to load with the class loader that loaded
jetty core classes (XmlConfiguration.class.getClassLoader())
looping through all the parents as well.
If still not successful, do a Class.forName()
Report ClassNotFoundException if not successful.
you can see it in the code of org.mortbay.util.Loader(http://grepcode.com is a great resource for a quick look under the hood)
It does load the class in your case, but apparently not with the right class loader.
I would now assume you have an extra jetty JAR somewhere on your classpath that interferes with the order of things.
Had a same issue caused by :
<useTestClasspath>true</useTestClasspath> (true instead of false)
That put a extra jetty jar in the classpath...
Including the dependency scope solved the error for me.
<scope>provided</scope>
In the pom.xml it looks like this,
<!-- JETTY DEPENDENCIES -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
in the jetty dependencies and the errors went off. And btw, the jetty version I'm using is 9.3.7.v20160115.
I had the same issue and fixed it but can't figure out why.
By changing
org.eclipse.jetty.webapp.WebAppContext
to
org.eclipse.jetty.maven.plugin.JettyWebAppContext
it started to work for some reason, can't figure out exactly why. Clearly maven plugin has something to do with it?