The import org.junit cannot be resolved - java

I need to solve a Java problem for an interview, and they have sent me the test class. It starts with
import org.junit.Before;
and also has the following syntax at places:
#RunWith(JUnit4.class)
...
#Before
...
#Test
I haven't used Java for a while, so this confuses me a little. I downloaded eclipse and when I tried to compile this test file, there are errors at the import and at the '#' signs. The import error throws:
The import org.junit cannot be resolved.
And the #RunWith is not even recognized, as it tries to resolve it to a type.

You need to add JUnit library to the classpath of your project. There are several choices to achieve it depending on your development setup.
Command line: In the case of command-line invocations, you will have to add junit.jar to the classpath of your application with java -cp /path/to/junit.jar. Take a look at the answers here.
Using eclipse: Eclipse distributions are bundled with this library and this is how you can use it for your project. Right-click on the eclipse project and navigate:
Properties -> Java Build Path -> Libraries -> Add Library -> JUnit ->
JUnit 3/4
In the scenarios where you want to use a different version of the jar, instead of clicking on Add Library above, you should click on Add External Jar and locate the library on the file system.

Right-click on the eclipse project and navigate to
Properties -> Java Build Path -> Libraries -> Add Library -> JUnit ->
JUnit 3/4
It works for me.

If you use maven and this piece of code is located in the main folder, try relocating it to the test folder.

If you are using eclipse and working on a maven project, then also the above steps work.
Right-click on your root folder.
Properties -> Java Build Path -> Libraries -> Add Library -> JUnit -> Junit 3/4
Step By Step Instructions here

you need to add Junit dependency in pom.xml file, it means you need to update with latest version.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

You can easily search for a line like #Test and then use the quick-fix add JUnit 4 library to the build path at this line. I think this is faster than adding JUnit manually to the project.

In starting code line copy past 'Junit' or 'TestNG' elements will show with Error till you import library with the Project File.
To import Libraries in to project:
Right Click on the Project --> Properties --> Java Build Path --> Libraries -> Add Library -> 'Junit' or 'TestNG'

If you are using Java 9 or above you may need to require the junit dependency in your module-info.java
module myModule {
requires junit;
}

If using Maven you can context click and run 'Maven/Update Project...'

Seems that the JUnit .jar file is not in the path. Also, make sure you are using JDK1.5 or above.

In case you want to create your own Test Class. In Eclipse go to File -> New -> J Unit Test Case. You can then choose all your paths and testing class setup within the wizard pop-up.

When you add TestNG to your Maven dependencies , Change scope from test to compile.Hope this would solve your issue..

I had the same problem right now. My solution: add JUnit to the pom.xml AND remove JUnit from the eclipse project properties (Java Build Path/Libraries).

If you use Maven with Eclipse then You need to follow the below steps.
1). Add Junit dependency to the pom.xml file
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
Note : Please get the latest from the following link
https://mvnrepository.com/artifact/junit/junit
2).On your test class (Ex. AdditionTest.class), you need to annotate with #Test on your test method (Ex. testAdd() )
Note : The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case.
public class AdditionTest {
#Test
public void testAdd()
{
// Test code here...
}
The moment/ the first time you annotate as "#Test" the IDE asks whether you need to Add Junit jar files to Class path. Once you accept this it will add the Junit jar file into the class path.
With this you can achieve the following imports
import org.junit.Test;
import static org.junit.Assert.*;
Regards

Update to latest JUnit version in pom.xml. It works for me.

Related

IDE does not recognize Assumptions

I am using Junit5, and my IDE (IntelijIdea) is not recognize Assumptions. I am actually do not know why, but may be there is some dependecy on Maven I do not connect into project. Below I will show you the sample of my code.
This is my Assumptions import.
import org.junit.jupiter.api.Assumptions;
And this is wrong code (I can not compile it, compiler does not know what is assumeTrue() )
#Test
#EnabledOnOs(OS.MAC)
void testInsertion() {
assumeTrue(isServerUp); //That place is crashing
assertThrows(NullPointerException.class, () -> Connection.insertTheInstance(person),
"");
If you are familiar with this case then, please, share you knowledge) Many thanks!
It's a import problem probably. Try:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
Check if maven import is ok
Close your project in intellij
Delete your .m2 folder in your HOME directory (user/yourusername in windows, /home in linux)
Execute in a terminal in your project: mvn dependency:purge-local-repository clean.
Open your project again
If it's not ok yet, try the junit 4.12. Its have Assumptions too.
assumeTrue method is part of JUnit 4, but you can also use it in JUnit 5 through the
org.junit.jupiter.api.Assumptions class.
For intelliJ - Junit5 combination, make sure to import the following in your class:
import static org.junit.jupiter.api.Assumptions.assumeTrue;

How to use scope "test" and junit correctly with maven and eclipse

I am trying to understand what I am doing wrong with junit-tests in Maven with eclipse. Mainly I have been just following this "getting started guide" for Maven:
https://spring.io/guides/gs/maven/
But for me it is not completely working like that when it comes to junit.
To follow the exact folder-structure from the example I have named my packages under src in eclipse:
main.java.hello
test.java.hello
My test class GreeterTest.java is in the package test.java.hello and has this content:
package test.java.hello;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.*;
import org.junit.Test;
import main.java.hello.Greeter;
public class GreeterTest {
private Greeter greeter = new Greeter();
#Test
public void greeterSaysHello() {
assertThat(greeter.sayHello(), containsString("Hello"));
}
}
In my pom.xml you find the dependency:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
Unfortunately eclipse sais "the import org.junit cannot be resolved."
If change the scope of the dependency from test to compile I do not get this error message, but that would be not the way how the scope is intended to be used, is it?
What do I need to change that also eclipse understands, that this class is a test-class and therefore all dependencies are actually available?
Best,Nils
The issue appears to be related to where Eclipse thinks your source tree starts. You have put your code in src/main/java/hello and src/main/test/hello but Eclipse thinks the source tree starts at src. So it thinks the other folders are packages and has given your classes package names like main.java.hello.Greeter.
The quickest way to fix this is to run on the command line:
mvn eclipse:eclipse
which uses maven to fix your eclipse projects. It will automatically set the source root to be the correct values. When it completes, right click on the project and select Refresh to see the updated project.
To fix this manually, you can right click on the project and choose Build Path > Configure Build Path and, in the Source tab on the right, ensure that the entire src/main/java (right up to java!) is included as the source folder. Do this by clicking Add Folder and selecting java in the tree under src - main. Do the same for src/main/test. Usually maven projects include src/main/resources as a source folder too.

Testing Java code with Groovy under Intellij: unable to resolve class GroovyTestCase

I need to write a short test for some Java code. I used CTRL+SHIFT+T to generate one with IntelliJ, and selected "Groovy JUnit" as the testing library, then wrote the following test:
package util
class FibonacciHeapTest extends GroovyTestCase {
FibonacciHeap<Integer> heap
void setUp() {
super.setUp()
heap = new FibonacciHeap<>()
}
void testAddInOrder() {
testForItems 1..1000
}
private void testForItems(Range<Integer> items) {
items.each {heap << it}
assertEquals heap.size, items.to
items.each {assertEquals heap.remove(), it}
}
}
However, when I right click on the test case in the project window, I don't get the "Run All Tests" option that I normally do with JUnit tests, and the compiler throws the following error:
Information:2/4/15 8:15 PM - Compilation completed with 2 errors and 0 warnings in 2 sec
/home/patrick/IdeaProjects/hackerrank/src/test/java/util/FibonacciHeapTest.groovy
Error:(3, 1) Groovyc: unable to resolve class util.FibonacciHeap
Error:(9, 1) Groovyc: unable to resolve class GroovyTestCase
Trying to import GroovyTestCase or FibonacciHeap manually causes the same error. IntelliJ does not add any import statements when I let autocomplete finish the names for me, like it usually would with Java code.
What am I doing wrong?
This worked for me :
Open Gradle window (on right side in my case)
Click on refresh button
Done
I had a similar problem with creating test classes in IntelliJ, and it was solved when creating a new directory outside of the com.company folder (where I had the class I wanted to test).
Create a new directory for the test classes on the same level as your src folder
Right click on your new test directory, and "Mark directory as" --> "Test Resources Root"
Now create a test class, which should automatically be added to your test directory.
Build -> Rebuild project in the IDE itself (as opposed to maven, in my case) did it for me.
In my case, what I did to resolve the issue was rather simple.
Close IntelliJ
Open the attached homepage...
Remove your project by clicking on the x then...
Click on Import Project, Navigate to the build.graddle file of your project and open.
That was it and all the Red highlightings disappeared.
maybe you need add groovy-all rather then groovy,such as :
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy.version}</version>
</dependency>
You have to configure Groovy SDK first. See the screenshot
More detailed description in the official document: Configuring Global, Project and Module SDKs
As #sman591 pointed out in a comment, if you are getting the error:
groovyc: unable to resolve class groovy.util.GroovyTestCase
and you already have groovy as a dependency then you are probably just missing the junit dependency.
In IntelliJ IDEA I re-imported the project. It worked then.
I closed idea. I removed .idea folder in the project. And I imported the project.
Then I needed to set up Groovy, see previous answers, mark test directory as test source in all modules of my project.
I was selecting the root folder which had build.gradle file in it, but it didn't work.
Steps followed are similar to #Pila
close the project from intellij
remove .idea, log, out folders
go to intellij dashboard
import project from existing resources
select build.gradle file <-- this is important
now you should see all the tasks are getting build in the background, and once build is finished all red lines are gone.

'No JUnit tests found' in Eclipse

So I'm new to JUnit, and we have to use it for a homework assignment. Our professor gave us a project that has one test class, BallTest.java. When I right click > Run as > JUnit Test, I get a popup error that says 'No JUnit tests found'. I know the question has been answered here(No tests found with test runner 'JUnit 4'), but closing eclipse, restarting, cleaning, and building doesn't seem to work. Below are screenshots of my run configuration, build path, and the class I'm trying to test.
BallTest.java
import static org.junit.Assert.*;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class BallTest {
Ball ball;
/**
* #throws java.lang.Exception
*/
#Before
public void setUp() throws Exception {
System.out.println("Setting up ...");
Point2D p = new Point2D(0,0);
ball = new Ball(p);
}
/**
* #throws java.lang.Exception
*/
#After
public void tearDown() throws Exception {
System.out.println("Tearing down ...");
ball = null;
}
/**
* Test method for {#link Ball#getCoordinates()}.
*/
#Test
public void testGetCoordinates() {
assertNotNull(ball); // don't need Assert. because of the import statement above.
Assert.assertEquals(ball.getCoordinates().getX(), 0);
Assert.assertEquals(ball.getCoordinates().getY(), 0);
}
/**
* Test method for {#link Ball#setCoordinates(Point2D)}.
*/
#Test
public void testSetCoordinates() {
Assert.assertNotNull(ball);
Point2D p = new Point2D(99,99);
ball.setCoordinates(p);
Assert.assertEquals(ball.getCoordinates().getX(), 99);
Assert.assertEquals(ball.getCoordinates().getY(), 99);
}
/**
* Test method for {#link Ball#Ball(Point2D)}.
*/
#Test
public void testBall() {
Point2D p = new Point2D(49,30);
ball = new Ball(p);
Assert.assertNotNull(ball);
Assert.assertEquals(ball.getCoordinates().getX(), 49);
Assert.assertEquals(ball.getCoordinates().getY(), 30);
//fail("Not yet implemented");
}
public static void main (String[] args) {
Result result = JUnitCore.runClasses(BallTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Right Click on Project > Properties > Java Build Path > Add the Test folder as source folder.
All source folders including Test Classes need to be in Eclipse Java Build Path. So that the sources such as main and test classes can be compiled into the build directory (Eclipse default folder is bin).
If none of the other answers work for you, here's what worked for me.
Restart eclipse
I had source folder configured correctly, and unit tests correctly annotated but was still getting "No JUnit tests found", for one project. After a restart it worked. I was using STS 3.6.2 based of eclipse Luna 4.4.1
right click -> build path -> remove from build path
and then again add it ->
Right click on the folder named 'Test' > Build Path > Use as Source Folder.
I had the same problem and solved like this:
I deleted #Test annotation and retyped it.
It just worked, I have no idea why.
It looks like you're missing the runner definition on your test class, that could be the cause:
import org.junit.runners.JUnit4;
#RunWith(JUnit4.class)
public class BallTest {
...
}
Right click your project ->Properties->Java Build Path and go to Source Tab then add your test src folder.
Select Project menu and unselect 'Build Automatically' option if selected
Select Clean and then select 'Build Automatically' option
Restart Eclipse and run your junit.
junit4 require that test classname should be use Test as suffix.
Any solution didn't work for me until I change the name of the my test method. When name of test method starts with "test" is OK.
I am new in android programing and it was for me big surprise.
I think you have created your test classes outside the src folder. You can solve above problem by two way:
Add your package name in java build path->source
Move your package/class in src folder
I have the same problem and solved in this way both solutions working fine.
Try this
Right Click on the Unit Test Class,
Select "Run As" -> Run Configuration
In the "Test" tab, make sure in the field "Test runner" select drop down "JUnit 4"
Click "Apply"
Now Run the test!
I solved the problem by configuring the build path.
Right click on the project(or any of the subfolders)-> Build path -> Configure build path. Once the property window opens up, click on the 'Source' tab and add your src and tst folders.
But this alone did not work for me.
Strangely, I had to retype the annotations.(Project->clean or restart might also have worked though).
Came across this problem while upgrading projects across eclipse versions. For e.g. junits running well in Mars2.0 did not run on Neon. The following worked for me.
Delete .settings folder. Import project into eclipse.
Remove source folders. Then again use the folders as source folders. e.g - remove src/main/java from build path as source folder. -> Ok -> Again make this folder as source folder. Repeat it for main/resources, test/java, test/resources
In Eclipse Photon you may need to add JUnit 4 or 5 to the build path. Right click #Test and select 'Add JUnit 4 to build path'.
Click 'Run'->choose your JUnit->in 'Test Runner' select the JUnit version you want to run with.
The run configuration for a test class can create another cause (and solution) for this problem.
If you go to Run (or Debug) Configurations (using cmd-3 or clicking on the small dropdown buttons in the toolbar) you can see a configuration created for every test class you've worked with. I found that one of my classes that wouldn't launch had a run configuration where the Test Method field had somehow gotten inadvertently populated. I had to clear that to get it to work. When cleared it shows (all methods) in light text.
I'll add that strangely — maybe there was something else going on — it also seemed not to work for me until I fixed the "Name" field as well so that it included only the class name like the other JUnit run configurations.
I was using #RunWith(Parameterized.class) but missed to add the #Parameters annotation in the public static parameters method. After adding the annotation it worked.
The best way to resolve this issue is to put public Access modifier for your Junit Test Case class name and then run the scenario by right click on your Junit test case class and run as Junit Test.
The solution was, after making a backup of the src/test folder, removing it from the filesystem, then creating it again.
That's after I did the "Remove from build path" hint and it screwed the folders when opening the project in STS 4.
I had this problem too with JUnit 5.4.2. I use Eclipse 2019-09 with gradle 5.3.1.
So I had to add this two dependencies to build.gradle file with right configuration for it (testImplementation and testRuntimeOnly):
apply plugin: "java"
//enabled the Gradle’s native JUnit 5 support
test {
useJUnitPlatform()
}
testImplementation group: "org.junit.jupiter", name: "junit-jupiter-api", version: "${junitVer}"
testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: "${junitVer}"
Some time if lots if Test files are there then Eclipse failed to pass -classpath options for all libs and path due to classpath param lenght limitations.
To Solve it go to Run
Configerations -> JUnit -> Your Project Config -> ClassPath -> Check "Use Temporary Jar Options"
At least it solved my problem.
Right Click on Project > Properties > Java Build Path > Libraries >
select classpath -> add Library -> Junit -> select junit version -> finish -> applay
Sometimes, it occurs when you add Junit Library in Module path. So, Delete it there and add in Class path.
Imported project in a new eclipse workspace, this resolved my issue.

Run As JUnit not appearing in Eclipse - using JUnit4

I'm trying to write JUnit4 tests for my web app, and they had been working fine previously. However, now when I try to run the tests by right clicking the class file -> Run As -> JUnit Test I don't see that option. I think it could be because a colleague committed some Eclipse settings/property files on accident that messed with mine. I'm using Eclipse Helios on a Mac running 10.6.X.
I noticed that the icons on the test classes changed from the "filled" J to a "bubble" J and I'm not sure if that is signifying some kind of problem:
I've double checked and made sure that JUnit4 is on my Build Path, and I've gone to the Eclipse -> Preferences -> JUnit pane and verified there are JUnit4 imports being used.
My test classes look like this:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration( { "classpath*:/resources/action-test-appconfig.xml" })
#Transactional
public class UserControllerTest extends BaseStrutsTestCase<UserController> {
/**
* Tests the ability of a user to change their login username
* #throws Exception
*/
#Test
public void testChangeLogin() throws Exception {
Any thoughts and suggestions are appreciated.
The problem is with the way you are trying to access and run java files in eclipse. You should be observing this empty 'J' icons on your java files. It is a classpath problem, when you click, you are actually accessing the file from the classpath.
To view the Java file, you have to add a reference to your project in the classpath and move it to the top of the classpath list.
Once you do that, then you should be able to run your junits.
I had the same issue, and I restarted eclipse and got "Run as JUnit test" back.
Looks like a bug in eclipse.
That kind of J icon filled to a "bubble" means that Eclipse doesn't recognize your project as a Java project, and therefore doesn't provide Java options such as Run as JUnit.
Try reimporting the project as a Java Project.
Try adding following dependency in the pom.xml of your project in which the test case is located:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.test</artifactId>
<version>3.1.1.RELEASE</version>
<scope>test</scope>
</dependency>

Categories

Resources