Search code examples
javamavenintellij-ideajunitclassnotfoundexception

Class not found exception in Junit (JAVA)


I've seen similar questions however all are related to maven (I'm not using maven). I'm running intellij and have the Junit.jar 4.12 added in the library. I can create test methods and classes.

The problem is that when I try to run my TestRunner() main method i instantly get the following error

Exception in thread "main" java.lang.ClassNotFoundException: TestRunner
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:122)

And the code looks like this:

import junit.framework.TestSuite;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
    public static void main(String[] args) {
        Result res = JUnitCore.runClasses(TestSuite.class);
        for (Failure fail : res.getFailures()) {
            System.out.println(fail.toString());
        }
        System.out.println(res.wasSuccessful());
    }
}

The thing that confuses me is that I had the exact same code in eclipse (for a previous project test) and it worked perfectly fine there. What am I missing?

  • Closing and restarting intellij did not work.
  • Re-importing libraries didn't change anything either.

Solution

  • Update, the problem was that I had not "Correctly" added the library. Apparently in Intellij, one must write @Test and then hit "Alt+enter" to prompt the auto fixes and choose the option to import JUnit that way. So it automatically adds it to the classpath. Which it didn't do properly if done manually.