Search code examples
javavisual-studio-codejunitjunit4

initializationError when trying to use JUnit in vscode


I am trying to do Java unit testing in Visual studio code using JUnit. I have:

  • Installed JUnit 4 jar to a folder
  • Made a reference to the .jar in VSCodes "Referenced Libraries" section
  • Made simple folder structure using no build tools

This is the directory structure of the project

(root project)
   |__ src/com/example
        |__ Add.java
   |__ src/test
        |__ TestAdd.java          

Add.java:

package src.com.example;

public class Add {
    public Add() {
    }
    
    public int add(int a, int b) {
        return a + b;
    }
}

TestAdd.java:

package src.test;

import static org.junit.Assert.assertEquals;
import org.junit.Test;
import src.com.example.Add;

public class TestAdd {

    public TestAdd() {
    }

    @Test
    public void testAdd() {
        Add add = new Add();
        
        assertEquals(2, add.add(1, 1));
    }
}

The issue

When I click run test, VSCode doesn't run the tests and says:

initializationError(src.test.TestAdd)

As the reason for not running the test under the testing tab in VSCode.

Screenshots: Folder structure + libraries: Folder structure + libraries Error shown: Error shown

Please be forgiving, this is my first StackOverflow question - apologies in advance!


Solution

  • If you want to introduce the JUnit4 dependencies without the build tools. You need to download 2 jars, and add both of them to the referenced libraries in VS Code. Check: https://github.com/junit-team/junit4/wiki/Download-and-Install#plain-old-jar