javamavenvisual-studio-codejunitimporterror

Why does vscode not recognize the import org.junit?


I am using maven to develop a java project within visual studio code, and am currently trying to write a test class. I have added junit as a dependency to my pom.xml file:

<dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
</dependency>

Currently, my class looks like this: (there are no problems with the Board class, and getOne() returns 1)

import org.junit.Test;

public class BoardTest {
    private Board board = new Board();

    @Test
    public void testOne() {
        assert(board.getOne() == 1);
    }
}

Initially, when I open the file, everything is fine, but as soon as I save, vscode generates 2 error messages, both of which go away when I close and reopen the file, but appear again after a save:

  1. "The import org.junit cannot be resolved"

  2. "Test cannot be resolved to a type"

Interestingly, even with these errors present, vscode gives me mouseover information for both the import and the @Test flag, as if it has actually resolved them correctly. I have run mvn install from the command line, and vscode even lists junit-4.12.jar in the project's java dependencies section.

Running mvn test yields the expected result (the test passes), and after mvn package, running the project's .jar file from the command line runs the project with no problems. Whenever I try to run the project from vscode, it gives me a notice that the build has failed, even if the error messages are not currently present (i.e. after I have opened the test class but before I have saved). If I tell vscode to proceed anyway, the project again runs fine. Trying to run the test from vscode works the same way (I get an error message, but the test passes as normal after I tell vscode to proceed anyway).

Any ideas as to what could cause this? Here are the current versions of everything that I am using:

JDK: openjdk v11.0.7

vscode: v1.45.1

maven: Apache Maven v3.6.3


Solution

  • Try this VS Code command...

    View -> Command Palette -> Java: Clean Java Language Server Workspace
    

    This command resolved my similar issue with VS Code not recognizing import org.json.* inside the .java files of a Gradle project even though Gradle would build and run successfully. This VS Code command is similar to IntelliJ's File -> Invalidate Caches and Restart in that it forces a refresh of the IDE's cache of available tokens and identifiers.

    Side Notes: