[java] The import org.junit cannot be resolved

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 in a while so this confuses me a little. I downloaded eclipse and when I try to compile this test file there's 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 because it tries to resolve it to a type.

This question is related to java eclipse

The answer is


Seem to Junit jar file is not in path also make sure you are using jdk1.5 or above.


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


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

enter image description here


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


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.


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> 

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


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'

Add Junit Libraries


you can easily search for a line like "@Test" and then use the quickfix "add junit 4 library to the build path" at this line. i think this is faster than adding junit manually to the project.


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


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;
}

Right-click on the eclipse project and navigate:

Properties -> Java Build Path -> Libraries -> Add Library -> JUnit -> Junit 3/4

It works on mine.