2
respostas

Problema Entre Junit + Spring + EnableCaching - Erro java.lang.IllegalStateException: Failed to load ApplicationContext

Recebo o erro "java.lang.IllegalStateException: Failed to load ApplicationContext" ao executar o teste do Junit:

package br.com.casadocodigo.loja.controllers;

import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.EnableCaching; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext;

import br.com.casadocodigo.loja.conf.AppWebConfiguration; import br.com.casadocodigo.loja.conf.JPAConfiguration; import br.com.casadocodigo.loja.confs.DataSourceConfigurationTest;

@WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {JPAConfiguration.class, AppWebConfiguration.class, DataSourceConfigurationTest.class}) @ActiveProfiles("test") public class ProdutosControllerTest {

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setup(){
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}

@Test
public void deveRetornarParaHomeComOsLivros() throws Exception{
    mockMvc.perform(MockMvcRequestBuilders.get("/")).andExpect(MockMvcResultMatchers.forwardedUrl("/WEB-INF/views/home.jsp"));
}

}

package br.com.casadocodigo.loja.controllers;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import br.com.casadocodigo.loja.dao.ProdutoDAO; import br.com.casadocodigo.loja.infra.FileSaver; import br.com.casadocodigo.loja.model.Produto; import br.com.casadocodigo.loja.model.TipoPreco; import br.com.casadocodigo.loja.validate.ProdutoValidation;

@Controller public class ProdutosController {

@Autowired
private ProdutoDAO produtoDAO;

@Autowired
private FileSaver file;

@RequestMapping("/produtos/cadastro")
public ModelAndView cadastroProdutoInit(Produto produto) {
    ModelAndView modelAndView = new ModelAndView("/produtos/cadastro");
    modelAndView.addObject("tipos", TipoPreco.values());

    return modelAndView;
}

@RequestMapping(value = {"/produtos"}, method = RequestMethod.POST)
@CacheEvict(value="HomeCacheIndex", allEntries=true)
public ModelAndView gravar(MultipartFile sumario,@Valid Produto produto, BindingResult result, RedirectAttributes redirectAttributes) {
    if (result.hasErrors()) {
        return cadastroProdutoInit(produto);
    }
    System.out.println("ProdutosController.grava()" + produto.toString()) ;
    String  path = file.gravar("Arquivo-Sumario", sumario);
    produto.setSumarioPath(path);
    produtoDAO.gravar(produto);
    ModelAndView modelAndView = new ModelAndView("redirect:produtos");
    redirectAttributes.addFlashAttribute("Sucesso", "Produto " + produto.getTitulo() + "Cadastrado com Sucesso");
    return modelAndView;
}

@RequestMapping(value = {"/produtos"}, method = RequestMethod.GET)
public ModelAndView listar() {
    List<Produto> lista = produtoDAO.listar();
    ModelAndView modelAndView = new ModelAndView("/produtos/lista");
    modelAndView.addObject("produtos", lista);

    return modelAndView;
}

@RequestMapping("/produtos/detalhe/{id}")
public ModelAndView detalhe(@PathVariable("id") Long id){
    ModelAndView modelAndView = new ModelAndView("/produtos/detalhe");
    Produto produto = produtoDAO.find(id);
    modelAndView.addObject("produto", produto);
    return modelAndView;
}


@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.addValidators(new ProdutoValidation());
}

}

Percebei que quando retiro o @EnableCaching do AppWebConfiguration e condigo funciona corretamente, podem me ajudar

2 respostas

Faltou a classe AppWebConfiguration

package br.com.casadocodigo.loja.conf;

import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit;

import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.guava.GuavaCacheManager; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.format.datetime.DateFormatter; import org.springframework.format.datetime.DateFormatterRegistrar; import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.support.StandardServletMultipartResolver; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.google.common.cache.CacheBuilder;

import br.com.casadocodigo.loja.controllers.HomeController; import br.com.casadocodigo.loja.dao.ProdutoDAO; import br.com.casadocodigo.loja.infra.FileSaver; import br.com.casadocodigo.loja.model.CarrinhoCompras;

@Configuration @EnableWebMvc @ComponentScan(basePackageClasses = { HomeController.class, ProdutoDAO.class, FileSaver.class, CarrinhoCompras.class }) @EnableCaching public class AppWebConfiguration extends WebMvcConfigurerAdapter {

@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
    InternalResourceViewResolver view = new InternalResourceViewResolver();
    view.setPrefix("/WEB-INF/views/");
    view.setSuffix(".jsp");
    view.setExposedContextBeanNames("carrinhoCompras");
    return view;
}

@Bean
public CacheManager CacheManager() {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder().maximumSize(100).expireAfterAccess(5,
            TimeUnit.HOURS);
    GuavaCacheManager manager = new GuavaCacheManager();
    manager.setCacheBuilder(builder);
    return manager;
}



@Bean
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource reloadable = new ReloadableResourceBundleMessageSource();
    reloadable.setBasename("/i18n/messages");
    reloadable.setDefaultEncoding("UTF-8");
    reloadable.setCacheSeconds(10);
    return reloadable;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LocaleChangeInterceptor());
}

@Bean
public LocaleResolver localeResolver() {
    return new CookieLocaleResolver();
}

@Bean
public DefaultFormattingConversionService MVCConversionService() {
    DefaultFormattingConversionService dfConversion = new DefaultFormattingConversionService();
    DateFormatterRegistrar registrar = new DateFormatterRegistrar();
    registrar.setFormatter(new DateFormatter("dd/MM/yyyy"));
    registrar.registerFormatters(dfConversion);
    return dfConversion;
}

@Bean
public MultipartResolver multipartResolver() {
    return new StandardServletMultipartResolver();
}

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

@Bean
public ViewResolver contentNegotiationViewResolver(ContentNegotiationManager contentNegocioMng) {
    List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>();
    viewResolvers.add(internalResourceViewResolver());
    viewResolvers.add(new JsonViewResolver());

    ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
    resolver.setViewResolvers(viewResolvers);
    resolver.setContentNegotiationManager(contentNegocioMng);
    return resolver;
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

}

Oi Vinicius, tudo bem?

Poste o erro completo para analisarmos, por favor.

Abraço!