Intellij “java: package org.junit does not exist”

2020-07-03 05:30发布

问题:

When i try to run my test i get the following Errors: I looked up on google and found somthing on google but this didn't help.

Error:(3, 24) java: package org.junit does not exist
Error:(3, 1) java: static import only from classes and interfaces
Error:(5, 17) java: package org.junit does not exist
Error:(6, 17) java: package org.junit does not exist
Error:(12, 10) java: cannot find symbol
    symbol:   class Before
    location: class edu.kit.ipd.swt1.SimpleEditMeTest
Error:(17, 10) java: cannot find symbol
    symbol:   class Test
    location: class edu.kit.ipd.swt1.SimpleEditMeTest
[...]

My test code:

package edu.kit.ipd.swt1;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;

public class SimpleEditMeTest {
private EditMe editMe;
@Before
public void setUp() throws Exception {
    editMe = new EditMe();
}
@Test
public void test() {
    assertNotNull(editMe.getFoo());
}
}

Screenshot of the whole project

Run configurations

Dependencies i.stack.imgur. com/OiQWU.png (Can't post more than 2 links)

回答1:

I had the same problem. In order to fix it I had to Open Module Settings for my project and manually add jar Dependencies junit-4.12.jar and hamcrest-core-1.3.jar which are contained in the IntelliJ installation lib directory.



回答2:

For anyone ending up here using maven, a couple of things to check:

  • (Sanity check) Have you added junit as a dependency in your pom.xml?
  • Have Intellij accepted your module as a maven module? Try Right clicking the module/project and select Add as Maven Project or perhaps Maven->Reimport
  • Are you using explicit version in your dependency declaration in your pom file? Like <version>4.12</version>. Try that. (You might not want to this because you want the version to be decided by a parent module. Read on.)
  • Have you remembered to add a dependencyManagement? Maven need it to resolve the correct version number if you don't want to have it explicitly in the current project. For me it refers to the parent project. Like this:
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.myorg</groupId>
            <artifactId>myproject-parent</artifactId>
            <version>${myproject.version}</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>


回答3:

I had the same problem. Adding JARs made no difference. I solved it by adding library (not JAR) dependency for Junit 5.3



回答4:

The solution to this is to add junit library as dependency to the project. This can be done by adding junit to global library and then hovering over the error(junit word) and right clicking to add junit to class path. alt+shift+ctrl+s to get project settings in the same either add junit to global library or to project section as mentioned by rob in his answer.