Java test initialization error

I know this question is pretty general but I haven't found any hints on why this error may show up. What are possible causes of seeing initalizationError in Eclipse window? I get no useful informat...

I know this question is pretty general but I haven’t found any hints on why this error may show up. What are possible causes of seeing initalizationError in Eclipse window? I get no useful information just a long and useless failure trace (not included here).

I am using JUnit 4.11

I have written the following code — just to see if it works:

package test;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class SimpleTest {

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
}

@Test
public void test() {
    assertEquals(15, 15);
}

}

Edit: Sorry In Eclipse window it’s called actually a «Failure trace»:

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing     at
java.lang.ClassLoader.defineClass1(Native Method)   at
java.lang.ClassLoader.defineClass(Unknown Source)   at
java.security.SecureClassLoader.defineClass(Unknown Source)     at
java.net.URLClassLoader.defineClass(Unknown Source)     at
java.net.URLClassLoader.access$100(Unknown Source)  at
java.net.URLClassLoader$1.run(Unknown Source)   at
java.net.URLClassLoader$1.run(Unknown Source)   at
java.security.AccessController.doPrivileged(Native Method)  at
java.net.URLClassLoader.findClass(Unknown Source)   at
java.lang.ClassLoader.loadClass(Unknown Source)     at
sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)  at
java.lang.ClassLoader.loadClass(Unknown Source)     at
org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
    at
org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at 
org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at
org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at
org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:26)
    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:33)
    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:25)
    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassNotFoundException:
org.hamcrest.SelfDescribing     at java.net.URLClassLoader$1.run(Unknown
Source)     at java.net.URLClassLoader$1.run(Unknown Source)    at
java.security.AccessController.doPrivileged(Native Method)  at
java.net.URLClassLoader.findClass(Unknown Source)   at
java.lang.ClassLoader.loadClass(Unknown Source)     at
sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)  at
java.lang.ClassLoader.loadClass(Unknown Source)     ... 25 more

guerda's user avatar

guerda

23.1k27 gold badges95 silver badges145 bronze badges

asked Mar 3, 2013 at 20:50

lixonn's user avatar

3

You’ve probably got one of two problems:

1) You’re using JUnit 4.11, which doesn’t include hamcrest. Add the hamcrest 1.3 library to your classpath.

2) You’ve got hamcrest 1.3 on your classpath, but you’ve got another version of either junit or hamcrest on your classpath.

For background, junit pre 4.11 included a cut down version of hamcrest 1.1. 4.11 removed these classes.

answered Mar 3, 2013 at 21:57

Matthew Farwell's user avatar

Matthew FarwellMatthew Farwell

60.4k18 gold badges126 silver badges169 bronze badges

5

For me it was a silly mistake. I inadvertently set the test as private instead of public:

@Test
private void thisTestWasCausingProblems() {
...
}

it should have been

@Test
public void thisTestIsOK() {
...
}

answered Feb 18, 2015 at 17:03

JACH's user avatar

JACHJACH

98610 silver badges20 bronze badges

4

Just try «Project > Clean…» — seems to be THE solution to many problems in Eclipse!

answered Aug 11, 2014 at 17:33

Henrik Schulze's user avatar

2

For me it was a missing static keyword in one of the JUnit annotated methods, e.g.:

@AfterClass
public static void cleanUp() {
    // ...
}

answered Nov 4, 2014 at 4:43

friederbluemle's user avatar

friederbluemlefriederbluemle

31.6k14 gold badges103 silver badges105 bronze badges

1

I received this error when the class was annotated with @Ignore and I tried to run a specific test via right clicking on it. Removing the @Ignore fixed the problem.

answered May 11, 2016 at 20:37

Luke's user avatar

LukeLuke

3,7024 gold badges30 silver badges49 bronze badges

I’ve experimented the exact same error. My problem was that the SetUp method I had created was declared as static.

If using eclipse, one could get a good description by clicking above the error and then checking the Failure trace window, just below… That’s how I found the real problem!

answered Nov 3, 2014 at 22:02

pablo.vix's user avatar

pablo.vixpablo.vix

2,0252 gold badges15 silver badges12 bronze badges

2

Also make sure you have all @Before-, @After— and whatever-JUnit-annotated methods declared as public. I had mine declared as private which caused the issue.

answered Dec 7, 2017 at 11:37

Monkey Supersonic's user avatar

1

This problem also occurs if you have a private Rule in you class:

@Rule
private TemporaryFolder folderRule;

Make it public.

answered Nov 24, 2016 at 16:10

T3rm1's user avatar

T3rm1T3rm1

2,1705 gold badges31 silver badges50 bronze badges

For me, it was due to the «return type» of the test method. It should be «void»

answered Aug 7, 2015 at 6:45

Karthik Murugan's user avatar

Karthik MuruganKarthik Murugan

1,4193 gold badges16 silver badges28 bronze badges

1

For me it was something to do with commons-logging. Since I was using

@RunWith(SpringJUnit4ClassRunner.class)

This resolved my issue

<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

answered Aug 16, 2015 at 3:24

Anand Rockzz's user avatar

Anand RockzzAnand Rockzz

5,7604 gold badges63 silver badges70 bronze badges

I had the same problem: Once it was excel path issue and other time it was missing @Test annotation.

Scorpio's user avatar

Scorpio

2,2791 gold badge29 silver badges45 bronze badges

answered Sep 28, 2015 at 10:31

yogendra's user avatar

2

I just had the same problem and the same message. I was able to get it fixed by importing to the Java Building Path the hamcrest-all-1.3.jar archive. I’m using a JUnit 4.12 version.

thor's user avatar

thor

21.1k29 gold badges85 silver badges167 bronze badges

answered Mar 26, 2016 at 3:26

JuanJoRoman's user avatar

My problem was that my parent class had no @Test methodes. I used there only some utilities. When I declared it abstract it works.

answered Jul 26, 2016 at 7:39

unrein's user avatar

My mistake was that I missed out @Test annotation on the test method.

answered Jan 16, 2018 at 7:10

user55926's user avatar

user55926user55926

3051 silver badge12 bronze badges

In my case, I had the following import in my test case:

import org.junit.jupiter.api.Test;

The correct import is:

import org.junit.Test;

Don’t just import any old Test type from junit, make sure you pick the correct one.

answered Jul 4, 2019 at 20:35

sgf's user avatar

Just if this helps, I was using Junit5 but the @RunWith(SpringRunner.class) was pointing towards import org.springframework.test.context.junit4.SpringRunner, which was messing around with things and hence was giving the initialization error.
I fixed this and it worked.

answered Sep 1, 2019 at 2:36

Divas's user avatar

DivasDivas

4452 gold badges7 silver badges14 bronze badges

1

In my case, I haven’t added the hamcrest-2.2 (formerly hamcrest-library-2.2) jar in my buildpath.
enter image description here

Make sure to include all dependency (and their dependency jars) jars with JUnit 4.13.2 to run your tests:

  • junit-4.13.2
  • hamcrest-core-2.2
  • hamcrest-2.2 (earlier hamcrest-library-2.2)

answered Sep 27, 2022 at 20:40

Yash Kanani's user avatar

1

I had the same issue… I was using maven building tool with JUnit dependency scope as ‘test’ and my @Test method was in main module.

To resolve, I’ve:
1. Commented the scope tag of JUnit dependency in the pom.xml
2. Rebuilt the package
3. Made sure the Test class has only one constructor

The issue can be two-folded:
1. The JUnit dependency is limited to test scope and the @Test method is in main scope
2. The test class has more than one constructor

answered Apr 27, 2015 at 19:25

Tony Puthenveettil's user avatar

I had the same problem, the solution for me is the following.

I had only install the junit.jar file from the web, but this library related with the hacrest-core.jar
When I downloaded the hacrest-core.jar file and added it in my project everything works fine.

answered Sep 18, 2015 at 8:28

KostasA's user avatar

KostasAKostasA

5,0226 gold badges20 silver badges29 bronze badges

For me the solution was one of the methods had to be void, I had it as Boolean.

answered Feb 18, 2016 at 14:16

PaN's user avatar

If you’re using the xtend language (or some other JVM lang with type inference) and haven’t explicitly defined the return type then it may be set to a non-void type because of the last expression, which will make JUnit fail.

answered Oct 19, 2016 at 13:00

Aykut Kllic's user avatar

Aykut KllicAykut Kllic

8789 silver badges14 bronze badges

I got another failure trace, but for future visitors using their favorite search engine:

For me the problem was that eclipse somehow decided to execute only a single method in my test class (I couldn’t figure out why, though).
Especially if you did not change anything in your setup, check your run configuration.

answered Jan 19, 2017 at 11:53

Qw3ry's user avatar

Qw3ryQw3ry

1,26914 silver badges29 bronze badges

In my case I have changed project name in pom.xml so the new target directory was generated and junit was searching classes in old directory. You need to change directory for JUnit also in Eclipse

Properties -> Java Build Path -> Source (Default output folder)

And also check because some of source folders listed in the same window may have former directory name. You need to change them too.

answered Sep 12, 2017 at 10:16

Dawid D's user avatar

Dawid DDawid D

97412 silver badges27 bronze badges

For me, I mistakenly added a parameter to the test method which caused initialization error.

answered Jan 3, 2018 at 2:54

Stanley's user avatar

StanleyStanley

5,0274 gold badges32 silver badges44 bronze badges

I had naively added junit-4.12.jar from poi.apache.org to my Build Path in Eclipse. I deleted it (Project, Properties, Java Build Path, Libraries, junit-4.12.jar, Remove) then in my test class allowed Eclipse to «Fix Project Setup» after pressing Ctrl-1. No more problems! :-)

answered Feb 25, 2019 at 17:35

i2B's user avatar

In my case, it was because I was not pointing to the correct package where I kept my feature (cucumber) file(s). This was a case of wrong path specification. See code snippet below:

import org.junit.runner.RunWith;

import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        
    features = "src/test/features",
    glue = "stepDefinitions"
        
        )

Below is the screenshot of the JUnit error: Junit Runner Error

Below is the Stack Trace in the console:

enter image description here

The final solution was I had to change the path to the correct package where my feature files were kept.

See the corrected code snippet below:

package cucumberOptions;

import org.junit.runner.RunWith;

import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        
    features = "src/test/java/features",
    glue = "stepDefinitions"
        
        )

public class TestRunner {

}

answered Jan 27, 2021 at 12:55

samson ojo's user avatar

  1. September 18th, 2010, 05:07 PM


    #1

    raphytaffy is offline


    Junior Member


    Default JUnit initialization error

    Hi all, I’m trying a simple JUnit test with Eclipse but I’m getting an initialization error (attached screenshot). Just looking for some help as to how to clear this error. Here are my classes:

    IntegerCalculator

    public class IntegerCalculator {
     
    	private int amount = 0;
     
    	public IntegerCalculator() {}
    	public IntegerCalculator(int amount) {
    		this.amount = amount;
    	}
     
    	public int getAmount() {
    		return amount;
    	}
     
    	public void add(int val) {
    		amount += val;	// This code is correct.
    	}
     
    	public void subtract(int val) {
    		amount = val;	// This code is wrong.
    	}
     
    	public void divide(int val) {
    		amount /= val;	// This code could generate and error.
    	}
     
    }

    IntegerCalculatorTest

    import static org.junit.Assert.*;
     
    import org.junit.Before;
    import org.junit.Test;
     
     
    public class IntegerCalculatorTest {
     
    	private IntegerCalculator n;
     
    	@Before
    	public void setUp() throws Exception {
    		n = new IntegerCalculator(7);
    	}
     
    	@Test
    	public void testAdd() {
    		n.add(5);
    		assertEquals("(7 + 5)", 12, n.getAmount());
    	}
     
    	@Test
    	public void testSubtract() {
    		n.subtract(3);
    		assertEquals("(7 - 3)", 4, n.getAmount());
    	}
     
    	@Test
    	public void testDivide() {
    		n.divide(0);
    		fail();
    	}
     
    }


  2. Default Related threads:


  3. September 20th, 2010, 03:53 PM


    #2

    j2me64 is offline


    Member


    Default Re: JUnit initialization error

    hello, i just imported your code in eclipse and i could compile and run your JUnit code succesful. what i created in eclipse is the following: i create a new source folder named test and then i right-clicked this folder and then choosed new -> JUnit Test Case and enter the name IntegerCalculatorTest and then i just copy/pasted your code and finished. when i created the JUnit Test Case i was asked if i wanted to create a JUnit 3 or JUnit 4 and i choosed JUnit 4. try the same and report the result.

    Last edited by j2me64; September 20th, 2010 at 04:00 PM.


  4. The Following User Says Thank You to j2me64 For This Useful Post:

    copeg (September 20th, 2010)


  5. September 20th, 2010, 05:33 PM


    #3

    raphytaffy is offline


    Junior Member


    Default Re: JUnit initialization error


Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    An unexpected, unwanted event that disturbed the normal flow of a program is called an Exception.

    There are mainly two types of exception in Java:

    1. Checked Exception

    2. Unchecked Exception

    ExceptionInInitializerError is the child class of the Error class and hence it is an unchecked exception. This exception is rise automatically by JVM when JVM attempts to load a new class as, during class loading, all static variables and static initializer block are being evaluated. This exception also acts as a signal that tells us that an unexpected exception has occurred in a static initializer block or in the assignment of value to the static variable.

    There are basically two cases when ExceptionInInitializerError can occur in a Java Program:

    1. ExceptionInInitializerError While Assigning Value To The Static Variable

    In the below example we assign a static variable to 20/0 where 20/0 gives an undefined arithmetic behavior and hence there occurs an exception in the static variable assignment and ultimately we will get ExceptionInInitializerError.

    Java

    class GFG {

        static int x = 20 / 0;

        public static void main(String[] args)

        {

            System.out.println("The value of x is " + x);

        }

    }

    2. ExceptionInInitializerError While Assigning Null Value Inside A Static Block

    In the below example we have declared a static block inside which we create a string s and assign a null value to it, and then we are printing the length of string, so we will get NullPointerException because we were trying to print the length of a string that has its value as null and as we see that this exception occurs inside the static block, so we will get ExceptionInInitializerError.

    Java

    class GFG {

        static

        {

            String s = null;

            System.out.println(s.length());

        }

        public static void main(String[] args)

        {

            System.out.println("GeeksForGeeks Is Best");

        }

    }

    How to Resolve Java.lang.ExceptionInInitializerError ?

    • We can resolve the java.lang.ExceptionInInitializerError by ensuring that static initializer block of classes does not throw any Runtime Exception.
    • We can resolve also resolve this exception by ensuring that the initializing static variable of classes also doesn’t throw any Runtime Exception.

    Понравилась статья? Поделить с друзьями:
  • Java syntax error on token delete this token
  • Java sql sqlrecoverableexception io error the network adapter could not establish the connection
  • Java sql sqlrecoverableexception io error socket read interrupted
  • Java sql sqlrecoverableexception io error got minus one from a read call
  • Java sql sqlexception network error ioexception socket failed eacces permission denied