springServletContext unsupportedOperation上的spring test失败

时间:2015-11-04 20:36:08

标签: spring spring-boot spring-test

我为Spring-Boot 1.3应用程序运行了一组集成测试。但我必须添加以下内容才能使我的最大会话工作:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements ServletContextAware {

...
 @Override
    public void setServletContext(ServletContext servletContext) {

        servletContext.getSessionCookieConfig().setHttpOnly(true);

        // causes an ApplicationEvent to be published to the Spring ApplicationContext every time a HttpSession commences or terminates
        servletContext.addListener(new HttpSessionEventPublisher());
    }

...
}

现在,当我运行测试时,我得到以下内容:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfig' defined in file [/Users/davidclark/projects/edmtotal/build/classes/main/com/edelweissco/dental/configuration/WebSecurityConfig.class]: Initialization of bean failed; nested exception is java.lang.UnsupportedOperationException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)

...
Caused by: java.lang.UnsupportedOperationException
    at org.springframework.mock.web.MockServletContext.addListener(MockServletContext.java:675)
    at com.edelweissco.dental.configuration.WebSecurityConfig.setServletContext(WebSecurityConfig.java:123)
...

这是一个示例测试类(但它们都有相同的例外):

@Transactional
public class ConfigurationSettingsTest extends BaseSpecification {

    @Autowired
    private ConfigurationSettings configurationSettings;

    @Autowired
    ConfigurableApplicationContext context

...
}

其中BaseSpecification为:

@ContextConfiguration(classes = MyApp, loader = SpringApplicationContextLoader)
@WebAppConfiguration
public class BaseSpecification extends Specification {

    @Value('${local.server.port}')
    private int serverPort;

    def setup() {
        RestAssured.port = serverPort;
    }
}

现在看来,当我运行集成测试时,MockServlet正在这里应用,并且它不支持。此功能。在调试时,我看到SpringBootMockServletContext正在尝试在setServletContext中设置,这就是异常的地方。

1 个答案:

答案 0 :(得分:1)

如果有其他人遇到此问题,我会发布我的回答。问题出在我的BaseSpecification中。我在其中添加了@WebAppConfiguration和@IntegrationTest,并从各个集成测试中删除了@IntegrationTest。显然,这实际上会以应有的方式创建ServletContext。

@ContextConfiguration(classes = MyApp, loader = SpringApplicationContextLoader)
@WebAppConfiguration
@IntegrationTest
public class BaseSpecification extends Specification {