由于某种原因,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 { //.. }
由于WebConfig
有ApplicationTestConfig
,因此应该排除这一个{@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中)的文件夹中,排除问题....