Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: javax/servlet/ServletContext Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: javax/servlet/ServletContext spring spring

Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: javax/servlet/ServletContext


It is a common issue. As Aniket Thakur said, the container will provide all Java servlet classes at runtime. But during the tests you need a jar to provide them.

The dependency you added to your pom is only the API : it declares everything but contains no implementation. So it will not help. Anyway, you declare it as "provided" which says to maven "don't worry, I know it will be on classpath".

You have to add a dependency that bring the implementation of all Java EE classes in test scope. In my projects I use glassfish even if I later use tomcat as a servlet container, but I once found the dependency googling for the same problem :

<dependency>    <groupId>org.glassfish</groupId>    <artifactId>javax.servlet</artifactId>    <version>3.0</version>    <scope>test</scope></dependency>

It should solve your NoClassDefFoundError problem.


Class is not found at runtime but is available at compile time. You need to add the corresponding jar so that it can be found at runtime. I generally use Ivy and in Eclipse I do

Project -> Properties ->Deployment Assembly -> Add -> java Build Path Enteries -> Ivy -> Finish

There must be something similar for Maven as well.

Also you need javax.servlet-api only during compile time as the container you are using to run the server will provide the actual APIs at runtime.