需要ServletContext来配置在具有@WebAppConfiguration

时间:2016-05-31 21:53:40

标签: java spring junit

由于某种原因,JUnit无法正确连接Spring上下文:

JUnit的

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { ApplicationTestConfig.class, CachingConfig.class }, loader = AnnotationConfigContextLoader.class)
@Transactional(transactionManager = "hibernateTransactionManager")
public class QueryTest extends AbstractTransactionalJUnit4SpringContextTests {
//...}

ApplicationTestConfig

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = { "com.hibernate.query.performance.persistence" }, transactionManagerRef = "jpaTransactionManager")
@EnableJpaAuditing
@PropertySource({ "classpath:persistence-postgresql.properties" })
@ComponentScan(basePackages = { "com.hibernate.query.performance" },
        excludeFilters = @ComponentScan.Filter(value = {WebMvcConfigurerAdapter.class, WebConfig.class}, type = FilterType.ASSIGNABLE_TYPE))
public class ApplicationTestConfig extends ApplicationConfig {
}

ApplicationConfig

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories (basePackages = { "com.hibernate.query.performance.persistence" }, transactionManagerRef = "jpaTransactionManager")
@EnableJpaAuditing
@PropertySource({ "classpath:persistence-postgresql.properties" })
@ComponentScan({ "com.hibernate.query.performance" })
public class ApplicationConfig { //.. }

由于WebConfigApplicationTestConfig,因此应该排除这一个{@ComponentScan.Filter

WebMvcConfig

@Configuration
@ComponentScan("com.hibernate.query.performance.api")
@EnableWebMvc 
public class WebConfig extends WebMvcConfigurerAdapter { //.. }

按照this answer中的建议在JUnit中设置@WebAppConfiguration仍会产生:

  

引起:org.springframework.beans.factory.BeanCreationException:   创建名为'defaultServletHandlerMapping'的bean时出错   在类路径资源中   [组织/ springframework的/网络/ servlet的/配置/注解/ DelegatingWebMvcConfiguration.class]:   通过工厂方法进行Bean实例化失败;嵌套异常是   org.springframework.beans.BeanInstantiationException:失败   实例化[org.springframework.web.servlet.HandlerMapping]:工厂   方法'defaultServletHandlerMapping'抛出异常;嵌套   异常是java.lang.IllegalArgumentException:ServletContext是   配置默认servlet处理所需的

更新

这也不起作用:

@ComponentScan(basePackages = { "com.hibernate.query.performance" },
        excludeFilters = @ComponentScan.Filter(classes = {WebMvcConfigurer.class}, type = FilterType.ASSIGNABLE_TYPE))

@ComponentScan(basePackages = { "com.hibernate.query.performance" },
        excludeFilters = @ComponentScan.Filter(pattern = "WebConfig", type = FilterType.REGEX))

UPDATE2 WebConfig放在标记为(在IDEA中)的文件夹中,排除问题....

0 个答案:

没有答案