JUnit5: Trouble Finding AssertEquals - java

I've set up JUnit in IntelliJ IDEA and have a bunch of tests with nothing in them. When I run them, they all pass as expected. However, when I type "assertEquals", it shows up in red. When I hover over it, it says "Cannot resolve method."
I've googled around and it looks like I need to do:
import static org.junit.Assert.*;
However, when I start typing import static org.junit., the next options are "*", "jupiter", or "platform"...
For reference, here's what a sample test looks like in my IDE:
#org.junit.jupiter.api.Test
void isButton() {
assertEquals()
}
Any idea how to fix this?
Thanks!

The full path to Assertions class is:
org.junit.jupiter.api.Assertions.assertEquals
Ensure you have added Jupiter API to your dependencies:
Gradle:
dependencies {
testCompile("org.junit.jupiter:junit-jupiter-api:5.9.0")
}
Maven:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.0</version>
<scope>test</scope>
</dependency>
There is a nice guide for Intellij IDEA and JUnit 5.
Take a look at it: Using JUnit 5 in IntelliJ IDEA

Maven
Verify your dependency specified in your POM file. You should have following nested within your dependencies element.
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.4.0-RC1</version>
<scope>test</scope>
</dependency>
If calling the assertions outside of your test classes, in your regular app classes, drop the <scope>test</scope> element.
Example class
Here is an example trivial test.
package work.basil.example;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Unit test for simple App.
*/
public class AppTest
{
/**
* Rigorous Test :-)
*/
#Test
public void shouldAnswerWithTrue()
{
assertTrue( true );
}
}
New junit-jupiter artifact
Note that as of 5.4.0 of JUnit, we can specify the new and very convenient single Maven artifact of junit-jupiter which in turn will supply 8 libraries to your project.

Related

Why am I getting NoClassDefFound org/hamcrest/SelfDescribing if I'm not using hamcrest at all in my Maven test?

I have been into this for a while. The related questions in StackOverflow are about the absence of the hamcrest-core JAR in the classpath of the project, and the solutions are all related to its addition. What I am trying to do is de opposite: removing this dependency from the classpath.
Consider a Maven project with a single test case:
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Unit test for simple App.
*/
public class AppTest {
/**
* Rigorous Test :-)
*/
#Test
public void shouldAnswerWithTrue() {
assertTrue(true);
}
}
Here the test shouldAnswerWithTrue invokes the method assertTrue in the class Assert from the dependency junit version 4.11 (declared in the POM). When I construct the corresponding call graph, the dependency hamcrest-core seems not to be used in this test case. hamcrest-core is a transitive dependency induced by the direct dependency junit. Therefore, I proceed to exclude it from the POM of my project as follows:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
However, when I execute mvn package, it triggers the following error:
java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing
I do not understand why Java is complaining about the interface SelfDescribing in a dependency that is not used at all in my test and in any of its methods calls. I have checked that no class from hamcrest-core is loaded from the Assert classes in JUnit.
So, Why I cannot exclude hamcrest-core? Why is this interface needed? Where is it called?
Because JUnit 4.11 actually depends on it at compile time: it uses it in its exception hierarchy. When the AssumptionViolatedException class is loaded, it will trigger a load of SelfDescribing.

AutoValue cannot be resolved to a type - Eclipse

Trying to use AutoValue of package com.google.auto.value.AutoValue in my java class and get error "AutoValue cannot be resolved to a type"
I have added this in pom.xml
<!-- https://mvnrepository.com/artifact/com.google.auto.value/auto-value -->
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
Java program :
package xxxx;
import ------
import com.google.auto.value.AutoValue;
#AutoValue
#DefaultCoder(SerializableCoder.class)
public abstract class ABC{
/**
* Manually create a test row.
*/
public static ABC create(List<Object> fields) {
return new AutoValue_ABC(fields); //error is here
}
public abstract List<Object> fields();
}
I tried the solutions like adding it by opening the project properties, browsing to Java Compiler -> Annotation Processing -> Factory Path, clicking on "Add External JARs" and then selecting 4 jar files - auto-service-1.0-rc1.jar ,
guava-16.0.1.jar ,
jsr-305-2.0.3.jar ,
auto-value-1.0-rc1.jar
Also tried adding m2e-apt plugin and Maven -> "Annotation processing" -> select "Automatically configure JDT APT..."
Still getting the errror "AutoValue cannot be resolved to a type"
Any Solutions?
Thanks in Advance.
Seems you are a bit outdated. Newest version of auto-value is 1.6.5.
You have to import not only auto-value, but also auto-value annotations. From official documentation of auto-value:
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value-annotations</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value</artifactId>
<version>1.6.2</version>
<scope>provided</scope>
</dependency>
That’s all you need for maven. For eclipse, you seem to have looked at Code Affine. Their article about auto-value is a bit confusing. You only need auto-value and auto-value-annotations. Guava, auto-service, and jsr are not necessary for use with auto-value.
At least, this worked for me.

Which class is loaded in a Maven project when multiple versions of same library are declared as dependencies?

The following is clearly bad practice but my question is out of pure curiosity: If I have a Maven project with two versions of the same library in the dependencies (e.g. jetty server in the pom.xml fraction below), then I import a class in my code (e.g. java code below), which version is the class picked up from?
<project>
....
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.3.0.v20150612</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>8.1.17.v20150415</version>
</dependency>
....
</project>
And the java code:
package test.hello;
import org.eclipse.jetty.server.Server;
public class Hello {
Server server;
public Hello() {
server = new Server();
}
}
Is the server object created from the old version class or the new version class? Maven does not complain about any ambiguity. It just loads a class; I don't know which.
Maven has nothing to do with loading jars or classes. Maven only gathers all the dependancy. Its upto your classloader to decide what to load when.
If you have two classes with the same binary name, and you want to know which one of them you are loading, you can only inspect the way that classloader tries to resolve a class name.

annotation before is missing value for the attribute value

I normally don't experience problem with JUnit annotation. But somehow today, with my new install of Netbeans 7.2, I am experiencing the following error when I use the #Before annotation:
annotation before is missing value for the attribute value
Does anyone know how to fix this?
UPDATE
I am writing a mavenized web-app.
For the TestCase, when I try to import org.junit.Before the program instead imports org.aspectj.lang.annotation.Before
Are you still getting the same error even after adding junit dependency in pom.xml?
Check to see that you are importing the right library i.e.
import org.junit.Before;
instead of
import org.aspectj.lang.annotation.Before;
Are you declarig a dependency to an up to date JUnit Version?
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
You should be able to import the right class: org.junit.Before.
This is a pretty old question but for anyone tripping over this error in 2023 after switching to the new JUnit Jupiter or using the latest spring-boot-dependencies bom file (which automatically configures you for Jupiter unless you override it):
Note that as of Jupiter, the org.junit.Before annotation was replaced with the org.junit.jupiter.api.BeforeAll annotation.
Some helpful URL references for the API changes:
Nice rundown of API changes from Junit4 to Jupiter
Javadoc for Junit Jupiter

NoSuchMethod error getting a gdata service

I get the following error:
Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.collect.ImmutableSet.of([Ljava/lang/Object;)Lcom/google/common/collect/ImmutableSet;
at com.google.gdata.wireformats.AltFormat$Builder.setAcceptableTypes(AltFormat.java:399)
at com.google.gdata.wireformats.AltFormat$Builder.setAcceptableXmlTypes(AltFormat.java:387)
at com.google.gdata.wireformats.AltFormat.<clinit>(AltFormat.java:49)
at com.google.gdata.client.Service.<clinit>(Service.java:558)
at testproject.TestProject.run(TestProject.java:22)
at testproject.TestProject.main(TestProject.java:31)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
This comes from the following code:
package testproject;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.util.*;
import java.util.logging.*;
public class TestProject {
public static void main(String[] args) {
try {
YouTubeService service = new YouTubeService("Test", "developerKey");
service.setUserCredentials("root#gmail.com", "pa$$word");
} catch (AuthenticationException ex) {
Logger.getLogger(TestProject.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
At first, I included every library in http://code.google.com/p/gdata-java-client/downloads/list and also imported much more than I needed to.
I've since removed the libraries I deemed unnecessary (thanks thinksteep). So the libraries I'm currently including are the following libraries:
mail.jar
activation.jar
ant.jar
gdata-core-1.0.jar
gdata-media-1.0.jar
guava-11.0.1.jar
gdata-youtube-2.0.jar
gdata-youtube-met-2.0.jar
(There are probably a few libraries there which are not necessary... But I'm at my whit's end...)
I'm just trying to test getting a YouTube service so I can get things going on this project, but no dice. Oh, and I've also included this library: http://code.google.com/p/guava-libraries because before I was getting a NoClassDefFound error and including that library seemed to solve it. Thank you in advance for the help!
Oh, and I also followed every step exactly (or at least I think so) in the gdata getting started guide. My test build was successful by the end... Thanks again!
Adding more than required may cause issue too. java.lang.NoSuchMethodError error typically happens in case where runtime couldn't find required method with exact signature. Possible causes are:
1) There might be mulitple jars with same code, which may cause wrong class get loaded.
2) Incompatable version of jar, the jar you have in classpath might be older version/newer version.
Make sure none of those cases happening.
Issue with latest version of gdata still referencing older guava methods
Check Out
http://code.google.com/p/gdata-java-client/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary&groupby=&sort=&id=344
Solution
I switched to guava-r07.jar located at
http://code.google.com/p/guava-libraries/downloads/detail?name=guava-r07.zip&can=4&q=
This got me past
ContactsService service = new ContactsService("");
Jar's in use:
Default Eclipse plugin jar's
gdata-base-1.0.jar
gdata-client-1.0.jar
gdata-contacts-3.0.jar
gdata-core-1.0.jar
gdata-media-1.0.jar
guava-r07.jar
Apache (servlet-api.jar)
JavaMail (mail.jar)
JavaBeans Activation Framework (activation.jar)
I dont know if its still relevant but i had the same exception
there is a problem with guava 11.02.jar (currently latest version)
when using guava-10.0.1 (can be found here) everything went well.
The Required library jars are as follows.
gdata-client-1.0.jar
gdata-core-1.0.jar
gdata-media-1.0.jar
gdata-youtube-2.0.jar
guava-11.0.2.jar
java-mail-1.4.4.jar
I am using the above mentioned library . Please make use of it ; because the ultimate aim is to get the YouTubeService Object. Check below for the code snippet.
package com.baba.test;
/*
* Author : Somanath Nanda
*/
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gdata.client.youtube.YouTubeQuery;
import com.google.gdata.client.youtube.YouTubeService;
public class Test {
private static final String CLIENT_ID = "XXXXXXXX.XXXXX.XXX.XXX";
private static final String DEVELOPER_KEY = "*********************************88";
public static void main(String[] args) throws MalformedURLException {
YouTubeService service = new YouTubeService(CLIENT_ID,DEVELOPER_KEY);
System.out.println("Service : "+service);
}
If you're using a build tool, such as Maven, then you could simply do something similar to the following example from a portion of the dependencies section in my pom.xml:
<!-- The mail dependency is required BEFORE the javaee-api dependency.
The gdata dependency (YouTube API) requires the mail dependency. -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.gdata</groupId>
<artifactId>core</artifactId>
<version>1.47.1</version>
</dependency>
I have added googlecollection-exp.jar into my build path then the previous execption was gone.
Pay attention to this jar gdata-core-1.0.jar I have the same problem, and I realized I have problem with this jar gdata-core-1.0.jar, and I found from website the same jar gdata-core-1.0.jar, but the content is different. After I replaced the new gdata-core-1.0.jar, problem solved.
So it's tricky that the jar with the same name but their contents are not the same. you thought you have the jar, actually it's not the right one
It could be that some of your jars would be having dependency on google/guava jars and if they're not in build path or if multiple of them are there it might raise inconsistency hence the error. A quick solution could be add latest version of guava to your pom
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>24.0-jre</version>
</dependency>
Now check in dependency hierarchy if any of your Jar apart from guava is referring to any other older jar of guava/google-collections. If so then exclude it, something like this
<exclusions>
<exclusion>
<groupId>com.google.collections</groupId>
<artifactId>google-collections</artifactId>
</exclusion>
</exclusions>

Categories