Search code examples
springspring-bootspring-boot-testshedlock

SpringBootTest failing with 'IllegalStateException - No ServletContext set'


I have a pretty simple @SpringBootTest :

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {...})
public class MyApplicationTest {

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

It was working as expected until we've added @EnableSchedulerLock (from Shedlock) on the MyApplication.java file.

Since, we're experiencing this issue :

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:582)
    ... 46 common frames omitted
Caused by: java.lang.IllegalStateException: No ServletContext set
    at org.springframework.util.Assert.state(Assert.java:73)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:483)

This happends when Spring tries to instanciate its resourceHandlerMapping :

@Bean
public HandlerMapping resourceHandlerMapping() {
    Assert.state(this.applicationContext != null, "No ApplicationContext set");
    Assert.state(this.servletContext != null, "No ServletContext set");
    ...

It's like this @Bean is created before the setServletContext (from WebMvcConfigurationSupport) is called.


Solution

  • As mentioned by Lukas, this error has been fixed in the latest version of Shedlock.

    Upgrading Shedlock's version from 2.2.0 to 2.5.0 fixes the issue.