web-dev-qa-db-fra.com

Impossible de charger ApplicationContext (avec annotation)

Ceci est ma classe pour le test.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
public class UserServiceImplIT {

    @Autowired
    private SampleService sampleService; 

    @BeforeClass
    public static void setUp() {
        System.out.println("-----> SETUP <-----");
    }

    @Test
    public void testSampleService() {
        assertTrue(true);
    }
}      

exception (plusieurs exceptions, main: Failed to load ApplicationContext,
Error creating bean with name 'defaultServletHandlerMapping'.
Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception;,
A ServletContext is required to configure default servlet handling)

Java.lang.IllegalStateException: Échec du chargement d'ApplicationContext sur org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext (DefaultCacheAwareContextLoaderDelegate.Java:124) sur org.springframework.estestContextAppontContextContextApplicationContext 83) sur org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies (DependencyInjectionTestExecutionListener.Java:117) sur org.springframework.test.context.support.DependencyInjectionTestExecutionListener.ProcessusInstack .context.TestContextManager.prepareTestInstance (TestContextManager.Java:228) sur org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest (SpringJUnit4ClassRunner.Java:230) at org.springframeRontprunstunRunstunRunstunstunRunstunRunstall SpringJUnit4ClassRunner.Java:289) sur org.junit.internal.runners.m odel.ReflectiveCallable.run (ReflectiveCallable.Java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock (SpringJUnit4ClassRunner.Java:291) at org.springframework.test.context.JunClassRunRunClass Java: 249) sur org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild (SpringJUnit4ClassRunner.Java:89) sur org.junit.runners.ParentRunner $ 3.run (ParentRunner.Java:290) sur org.jun. ParentRunner $ 1.schedule (ParentRunner.Java:71) at org.junit.runners.ParentRunner.runChildren (ParentRunner.Java:288) at org.junit.runners.ParentRunner.access $ 000 (ParentRunner.Java:58) chez org.junit .runners.ParentRunner $ 2.evaluate (ParentRunner.Java:268) at org.junit.internal.runners.statements.RunBefores.evaluate (RunBefores.Java:26) at org.springframework.test.context.junit4.statementssRassBeforeCeforeCalles. évaluer (RunBeforeTestClassCallbacks.Java:61) sur org.springframework.test.context.junit4.statements.RunAfterTestCla ssCallbacks.evaluate (RunAfterTestClassCallbacks.Java:70) sur org.junit.runners.ParentRunner.run (ParentRunner.Java:363) sur org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run (SpringJUnit4ClassRunner.run (Java193) .junit.runner.JUnitCore.run (JUnitCore.Java:137) à com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs (JUnit4IdeaTestRunner.Java:78) à com.intellij.rt.execution.jStartStartStart : 212) sur com.intellij.rt.execution.junit.JUnitStarter.main (JUnitStarter.Java:68) sur Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) sur Sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.Java ) sur Sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.Java:43) sur Java.lang.reflect.Method.invoke (Method.Java:491) sur com.intellij.rt.execution.application.AppMain.main (AppMain.) Java: 140) Causé par: org.springframework.beans.factory.BeanCreationException: erreur lors de la création du bean avec le nom 'defa ultServletHandlerMapping 'défini dans la classe org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: l'instanciation du bean via la méthode d'usine a échoué; l'exception imbriquée est org.springframework.beans.BeanInstantiationException: échec de l'instanciation de [org.springframework.web.servlet.HandlerMapping]: la méthode d'usine 'defaultServletHandlerMapping' a levé l'exception; L'exception imbriquée est Java.lang.IllegalArgumentException: un ServletContext est requis pour configurer la gestion des servlets par défaut sur org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.Java:599) sur org.springfamework.supps.s.org AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.Java:1123) à org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.Java:1018) à org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.Java: 510) sur org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.Java:482) sur org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObjects (RésuméBeanBeanFactory Factory $ 1.getObjects). beans.factory.support.DefaultSingletonBeanRegis try.getSingleton (DefaultSingletonBeanRegistry.Java:230) à org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.Java:302) à org.springframework.beans.factory.support.AbstractBeanFactory (FactoryBeanFactory.get.BeanFactory.Factory). 197)

AppConfig - fichier de configuration de base.

@Configuration
@ComponentScan("ru.moneymanager.web")
@EnableWebMvc
@EnableTransactionManagement
@PropertySource(value = {"classpath:application.properties"})
@Import({SecurityConfig.class,})
public class AppConfig {

    @Bean
    public SampleService getSampleService() {
        return new SampleServiceImpl();
    }

    @Bean
    public InternalResourceViewResolver setupViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/pages/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);

        return resolver;
    }

    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[]{"ru.moneymanager.web"});
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        return properties;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(s);
        return txManager;
    }
}       

SecurityConfig

@Configuration
@ComponentScan("ru.moneymanager.web")
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    AuthenticationService authenticationService;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);
        // отключена защита csrf на время тестов
        http.csrf().disable().addFilterBefore(filter,CsrfFilter.class);
        http.authorizeRequests().antMatchers("/account/**").hasRole("USER")
            .antMatchers("/user/**").hasRole("ADMIN")
            .and().formLogin();
    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(authenticationService);
    }   
}       

autres fichiers de configuration config
ce projet en git projet
dis moi ce qui ne va pas? Pourquoi l'erreur?

11
makson

Votre test nécessite un ServletContext: ajoutez @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

... ou regardez ici pour d'autres options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

[~ # ~] mise à jour [~ # ~] Dans Spring Boot 1.4.x et supérieur @WebIntegrationTest n'est plus préféré. @SpringBootTest ou @WebMvcTest

20
ndrone