Exception in thread "main" java.lang.NoClassDefFoundError: org/mockito/Mockito

12.5k views Asked by At

I'm newbie with Mockito and trying to lean from Here, All configuration I have done (Using Win-10) which mentioned in the tutorial.

Setting in Environment variable :

enter image description here

Mockito version :

<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>2.0.2-beta</version>
    <scope>test</scope>
</dependency>

I've started with the example mentioned in the same. but while I do run the test my class it shows below exception :

Exception in thread "main" java.lang.NoClassDefFoundError: org/mockito/Mockito
  at com.mockitotest.PortfolioTester.setUp(PortfolioTester.java:23)
  at com.mockitotest.PortfolioTester.main(PortfolioTester.java:14)
Caused by: java.lang.ClassNotFoundException: org.mockito.Mockito
  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)
  ... 2 more

I don't know what went wrong here. Can someone help me ?

2

There are 2 answers

0
Ahmad Shahwan On BEST ANSWER

The scope test indicates that the dependencies (binary files) are only used using maven's test phase. They are not delivered with the final target jar though. So if you run tests yourself (rather than letting maven do it), you'd better leave the default runtime scope, as follows:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>2.0.2-beta</version>
</dependency>
0
rogerdpack On

As a note I got this in the following situation.

A depends on B. B has a "compile" dependency on Mockito, and uses Mockito in its "normal source code".

A has a dependency on B, and on Mockito.

And then that same message "NoClassDefFound org.mockito.Mockito".

Turns on B's pom's "dependency on Mockito" was inheriting "test" from a parent. Apparently this "more local dependency" overrides the other one.

Making it problematic to share Mockito as a non-test dependency. Unless it's always and only used for unit tests, then it'll be available.