Spring @WebAppConfiguration Annotation Example

0

We will use spring @WebAppConfiguration annotation to test the web controllers. @WebAppConfiguration is a class-level annotation that will load web specific ApplicationContext, that is, WebApplicationContext. In this article we will show you how to inject WebApplicationContext and run integration tests.

The default path to the root of the web application is src/main/webapp. One may override it by passing a different path to the @WebAppConfiguration.

@WebAppConfiguration must be used in conjunction with @ContextConfiguration.
In the below test class, we load WebApplicationContext and MockServletContext using the @WebAppConfiguration annotation and inject their instances using @Autowired.
In test testGetRequest(), we run a request which in turn calls the controller method and then print the response.

SpringWebAppConfigurationExample:

package com.javarticles.spring;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

import java.net.URI;

import javax.servlet.ServletContext;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockServletContext;
import org.springframework.stereotype.Controller;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.util.UriComponentsBuilder;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class SpringWebAppConfigurationExample {
    @Autowired
    protected WebApplicationContext wac;

    @Autowired
    protected MockServletContext mockServletContext;

    private MockMvc mockMvc;

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

    @Test
    public void verifyWac() {
        ServletContext servletContext = wac.getServletContext();
        Assert.assertNotNull(servletContext);
        Assert.assertTrue(servletContext instanceof MockServletContext);
        for (String beanName : wac.getBeanDefinitionNames()) {
            if (beanName.contains("springCustomContextConfigurationExample")) {
                System.out.println("Bean Name: " + beanName);
                System.out.println("Bean " + wac.getBean(beanName));
            }
        }
    }

    @Test
    public void testGetRequest() throws Exception {
        String id = "hello";
        URI url = UriComponentsBuilder.fromUriString("/greet").pathSegment(id)
                .build().encode().toUri();
        System.out.println("Call " + url + ", result: " + 
                mockMvc.perform(get(url)).andReturn().getResponse().getContentAsString());
        mockMvc.perform(get(url)).andExpect(status().isOk())
                .andExpect(content().string("hello world"));
    }

    @Configuration
    @EnableWebMvc
    static class WebConfig extends WebMvcConfigurerAdapter {

        @Bean
        public GreetController greetController() {
            return new GreetController();
        }
    }

    @Controller
    private static class GreetController {

        @RequestMapping(value = "/greet/{id}", method = RequestMethod.GET)
        @ResponseBody
        public String getCircuit(@PathVariable String id) {
            return id + " world";
        }
    }
}

Output:

Feb 10, 2016 11:22:31 PM org.springframework.test.context.support.AbstractContextLoader generateDefaultLocations
INFO: Could not detect default resource locations for test class [com.javarticles.spring.SpringCustomContextConfigurationExample]: no resource found for suffixes {-context.xml}.
Feb 10, 2016 11:22:31 PM org.springframework.test.context.support.AbstractDelegatingSmartContextLoader processContextConfiguration
INFO: AnnotationConfigWebContextLoader detected default configuration classes for context configuration [[email protected] declaringClass = 'com.javarticles.spring.SpringCustomContextConfigurationExample', classes = '{class com.javarticles.spring.SpringCustomContextConfigurationExample$WebConfig}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.test.context.ContextLoader'].
Feb 10, 2016 11:22:31 PM org.springframework.test.context.web.WebTestContextBootstrapper getDefaultTestExecutionListenerClassNames
INFO: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
Feb 10, 2016 11:22:31 PM org.springframework.test.context.web.WebTestContextBootstrapper instantiateListeners
INFO: Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
Feb 10, 2016 11:22:31 PM org.springframework.test.context.web.WebTestContextBootstrapper instantiateListeners
INFO: Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
Feb 10, 2016 11:22:31 PM org.springframework.test.context.web.WebTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: [or[email protected]6bdf28bb, org.springframework.test[email protected]6b71769e, org.springframewor[email protected]2752f6e2, org.springfra[email protected]e580929]
Feb 10, 2016 11:22:31 PM org.springframework.web.context.support.GenericWebApplicationContext prepareRefresh
INFO: Refreshing org.s[email protected]15975490: startup date [Wed Feb 10 23:22:31 IST 2016]; root of context hierarchy
Feb 10, 2016 11:22:31 PM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/greet/{id}],methods=[GET]}" onto public java.lang.String com.javarticles.spring.SpringCustomContextConfigurationExample$MyController.getCircuit(java.lang.String)
Feb 10, 2016 11:22:31 PM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for @ControllerAdvice: org.s[email protected]15975490: startup date [Wed Feb 10 23:22:31 IST 2016]; root of context hierarchy
Feb 10, 2016 11:22:31 PM org.springframework.mock.web.MockServletContext log
INFO: Initializing Spring FrameworkServlet ''
Feb 10, 2016 11:22:31 PM org.springframework.test.web.servlet.TestDispatcherServlet initServletBean
INFO: FrameworkServlet '': initialization started
Feb 10, 2016 11:22:31 PM org.springframework.test.web.servlet.TestDispatcherServlet initServletBean
INFO: FrameworkServlet '': initialization completed in 11 ms
Bean Name: springCustomContextConfigurationExample.WebConfig
Bean com.javarticles.spring.SpringCustomContext[email protected]50eac852
Feb 10, 2016 11:22:31 PM org.springframework.mock.web.MockServletContext log
INFO: Initializing Spring FrameworkServlet ''
Feb 10, 2016 11:22:31 PM org.springframework.test.web.servlet.TestDispatcherServlet initServletBean
INFO: FrameworkServlet '': initialization started
Feb 10, 2016 11:22:31 PM org.springframework.test.web.servlet.TestDispatcherServlet initServletBean
INFO: FrameworkServlet '': initialization completed in 1 ms
Call /greet/hello, result: hello world
Feb 10, 2016 11:22:31 PM org.springframework.web.context.support.GenericWebApplicationContext doClose
INFO: Closing org.s[email protected]15975490: startup date [Wed Feb 10 23:22:31 IST 2016]; root of context hierarchy

Download the source code

This was an example about spring annotation @WebAppConfiguration.

You can download the source code here: springWebAppConfigurationAnnotationExample.zip
Share.

Comments are closed.