DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Andreas has posted 2 posts at DZone. View Full User Profile

Testing New Bean Scopes With Spring 2.0

11.15.2006
| 1119 views |
  • submit to reddit
        
import javax.servlet.FilterChain;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.AbstractSingleSpringContextTests;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.filter.RequestContextFilter;

abstract public class AbstractRequestContextFilterTestBase extends
		AbstractSingleSpringContextTests {

	private static MockServletContext context;

	private MockHttpServletResponse response;

	private MockHttpServletRequest request;

	private static MockHttpSession session;

	private static RequestContextFilter contextFilter;

	static {

		context = new MockServletContext();

		MockFilterConfig filterConfig = new MockFilterConfig(context,
				"filterConfig");

		contextFilter = new RequestContextFilter();
		contextFilter.setFilterConfig(filterConfig);

		session = new MockHttpSession(context);
	}

	@Override
	protected void onSetUp() throws Exception {
		super.onSetUp();

		// new request/response for every test method
		request = new MockHttpServletRequest(context);
		request.setSession(session);
		response = new MockHttpServletResponse();
	}

	@Override
	protected ConfigurableApplicationContext loadContextLocations(
			String[] locations) throws Exception {

		if (logger.isInfoEnabled()) {
			logger.info("Loading web application context for: "
					+ StringUtils.arrayToCommaDelimitedString(locations));
		}

		XmlWebApplicationContext ctx = new XmlWebApplicationContext();
		ctx.setConfigLocations(locations);
		ctx.setServletContext(context);
		ctx.refresh();
		return ctx;
	}

	protected final class FilterTest {

		private FilterChain chain;

		public FilterTest(FilterChain chain) {
			this.chain = chain;
		}

		// execute the filter
		public final void run() throws Exception {
			contextFilter.doFilter(request, response, chain);
		}
	}

}