Всем привет.
Пытаюсь запустить юнит-тесты для Spring 5. Есть три конфигурационных файла.
RootConfig:
@Configuration
@ComponentScan(basePackages = {"ru.example"})
@PropertySource("classpath:/config/app.properties")
public class RootConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
TransactionManagerConfig:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("ru.example.repository")
@EntityScan("ru.example.domain")
public class TransactionManagerConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws PropertyVetoException {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
entityManagerFactoryBean.setPackagesToScan("ru.example.domain");
return entityManagerFactoryBean;
}
@Bean
public JpaTransactionManager transactionManager() throws PropertyVetoException {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
private DataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/example");
dataSource.setUser("root");
dataSource.setPassword("root");
dataSource.setMaxPoolSize(20);
dataSource.setMinPoolSize(3);
dataSource.setMaxStatements(100);
dataSource.setPreferredTestQuery("SELECT 1");
dataSource.setTestConnectionOnCheckout(true);
return dataSource;
}
}
WebConfig:
@Configuration
@EnableWebMvc
@ComponentScan({"ru.example"})
public class WebConfig implements WebMvcConfigurer {
@Bean
@SuppressWarnings("unused")
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**")
.addResourceLocations("/");
}
}
Зависимости такие (что касается спринга и джейюнита):
testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: JUNIT_VERSION
testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: JUNIT_VERSION
testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: '5.3.1'
testCompile group: 'org.mockito', name: 'mockito-core', version: '2.22.0'
testCompile group: 'org.springframework', name: 'spring-test', version: SPRING_VERSION
testCompile group: 'org.hamcrest', name: 'hamcrest-library', version: '1.3'
testCompile group: 'com.jayway.jsonpath', name: 'json-path-assert', version: '2.4.0'
compile group: 'org.springframework', name: 'spring-webmvc', version: SPRING_VERSION
compile group: 'org.springframework', name: 'spring-web', version: SPRING_VERSION
compile group: 'org.springframework', name: 'spring-jdbc', version: SPRING_VERSION
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.0.5.RELEASE'
SPRING_VERSION = '5.1.0.RELEASE'
JUNIT_VERSION = '5.3.1'
Приложение нормально запускается и работает. Пытаюсь создать тесты.
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
RootConfig.class,
TransactionManagerConfig.class,
WebConfig.class
})
class OrderServiceImplTest {
@Test
void save() {
}
}
Падает со следующим стектрейсом:
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.instantiate(ConstructorResolver.java:620)
... 94 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:486)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$b4bf2d2e.CGLIB$resourceHandlerMapping$34(<generated>)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$b4bf2d2e$$FastClassBySpringCGLIB$$d653d6e3.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$b4bf2d2e.resourceHandlerMapping(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 95 common frames omitted
Подскажите, как правильно запустить Spring-тесты с JUnit 5 и что я делаю не так?
Похоже, что вам надо добавить @RunWith(SpringRunner.class):
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
RootConfig.class,
TransactionManagerConfig.class,
WebConfig.class
})
Оказалось, что для того, чтобы ServletСontext был проинициализирован, необходимо добавить аннотацию @WebAppConfiguration
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
RootConfig.class,
TransactionManagerConfig.class,
WebConfig.class
})
@WebAppConfiguration
class OrderServiceImplTest {
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости