@ContextConfiguration不只引入指定的配置类

时间:2018-12-12 15:43:05

标签: java spring spring-mvc

我注意到使用@EnableWebMvc运行测试时遇到以下错误:A ServletContext is required to configure default servlet handling。通过注释掉@EnableWebMvc暂时解决了这个问题,然后我的测试全部通过了,但是我希望在我的Web应用程序中使用它。

我读过in this post,我可以将@EnableWebMvc放在测试(?)中未包含的另一个配置类中。所以我尝试了这个:

AppConfig.java

@Configuration
@ComponentScan(basePackages = "biz.martyn.budget")
@PropertySource("classpath:prod.properties")
@EnableTransactionManagement
public class AppConfig {

    @Autowired
    private Environment env;

    @Bean(name = "dataSource", destroyMethod = "shutdown")
    @Profile("prod")
    public DataSource dataSourceForProd() {...

WebMvcConfig.java

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver viewResolver() {...

然后在我正在尝试的测试中:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class)
@Transactional
public class FundRepositoryTest {...

但是,我仍然在测试中看到相同的错误。我知道是@EnableWebMvc,因为我删除它时它们都通过了。我是否对@ContextConfiguration批注的工作方式有误解?顺便说一句,如果有帮助,我正在对所有spring- *依赖项使用Spring 4.2.2.RELEASE版本。

以下也是我在测试运行中看到的错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)

1 个答案:

答案 0 :(得分:0)

我仍然不确定为什么@ContextConfiguration注释不仅接受我提供的类,而且发现添加到每个测试类的@WebAppConfiguration提供了所需的上下文:< / p>

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class)
@Transactional
@WebAppConfiguration // <-- added this
public class FundRepositoryTest {...

这是我需要添加的附加注释,但是我的测试现在可以运行。

相关问题