Getting java.lang.ClassNotFoundException: javax.servlet.ServletContext in JUnit

1.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

2.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/spring-mvc.xml")
@WebAppConfiguration

These advices helped me.


I got a similar error. Commenting out

<scope>provided</scope>

under the spring-boot-starter-tomcat dependency resolved it for me.


You have a single xml file for your ApplicationContext in this file there is a <mvc:annotation-driven /> tag. This tag loads different web related resources (view resolvers, handler mappings etc.) and as such requires the servlet api to be available.

You already should have the servlet api on your classpath as a provided dependency in maven.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Next to that you might want to remove the <mvc:annotation-driven /> tag and put it in a seperate configuration file. This is also a tag which should (in general speaking) be loaded by the DispatcherServlet. (I assume here the applicationContext.xml is, as default, loaded by the ContextLoaderListener).