Search code examples
javamaventestingjerseyhk2

Class def not found: org/glassfish/hk2/ComponentException


I need to write junit tests for Jersey application. Now I want to test dependency injection and the problem is I created class like this:

@RunWith(Hk2Runner.class)
public class BinderTest {
    @Inject
    private SomeClass someClass;

    @Test
    public void passingTest() {
        someClass.getSomething("asd", "asd", "asd");
        Assert.assertTrue(true);
    }
}

When run, the output is:

java.lang.NoClassDefFoundError: org/glassfish/hk2/ComponentException
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368)

I am trying to find dependency having that class to add to the pom.xml file but found nothing.. Do you guys know which maven dependency contains mentioned ComponentException class?

Dependency added in order to have Hk2Runner class:

<dependency>
    <groupId>org.glassfish.hk2</groupId>
    <artifactId>auto-depends</artifactId>
    <version>2.0.5</version>
</dependency>

Solution

  • Since you are using the old auto-depends dependency, you should also add the hk2-deprecated dependency:

    <dependency>
        <groupId>org.glassfish.hk2</groupId>
        <artifactId>hk2-deprecated</artifactId>
        <version>2.0.5</version>
        <scope>test</scope>
    </dependency>
    

    Another solution would be to replace the auto-depends dependency with the new hk2-testing and extend from org.jvnet.hk2.testing.junit.HK2Runner class.

    <dependency>
        <groupId>org.glassfish.hk2</groupId>
        <artifactId>hk2-testing</artifactId>
        <version>2.3.0</version>
        <scope>test</scope>
    </dependency>
    
    public class BinderTest extends HK2Runner { }