001/* 002 * Copyright 2002-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.test.web.servlet; 018 019import java.util.List; 020 021import javax.servlet.Filter; 022import javax.servlet.ServletException; 023 024import org.springframework.core.NestedRuntimeException; 025import org.springframework.lang.Nullable; 026import org.springframework.mock.web.MockServletConfig; 027import org.springframework.web.context.WebApplicationContext; 028 029/** 030 * Base class for MockMvc builder implementations, providing the capability to 031 * create a {@link MockMvc} instance. 032 * 033 * <p>{@link org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder}, 034 * which derives from this class, provides a concrete {@code build} method, 035 * and delegates to abstract methods to obtain a {@link WebApplicationContext}. 036 * 037 * @author Rossen Stoyanchev 038 * @author Rob Winch 039 * @author Stephane Nicoll 040 * @since 3.2 041 */ 042public abstract class MockMvcBuilderSupport { 043 044 protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig, 045 WebApplicationContext webAppContext, @Nullable RequestBuilder defaultRequestBuilder, 046 List<ResultMatcher> globalResultMatchers, List<ResultHandler> globalResultHandlers, 047 @Nullable List<DispatcherServletCustomizer> dispatcherServletCustomizers) { 048 049 TestDispatcherServlet dispatcherServlet = new TestDispatcherServlet(webAppContext); 050 if (dispatcherServletCustomizers != null) { 051 for (DispatcherServletCustomizer customizers : dispatcherServletCustomizers) { 052 customizers.customize(dispatcherServlet); 053 } 054 } 055 try { 056 dispatcherServlet.init(servletConfig); 057 } 058 catch (ServletException ex) { 059 // should never happen.. 060 throw new MockMvcBuildException("Failed to initialize TestDispatcherServlet", ex); 061 } 062 063 MockMvc mockMvc = new MockMvc(dispatcherServlet, filters); 064 mockMvc.setDefaultRequest(defaultRequestBuilder); 065 mockMvc.setGlobalResultMatchers(globalResultMatchers); 066 mockMvc.setGlobalResultHandlers(globalResultHandlers); 067 068 return mockMvc; 069 } 070 071 072 @SuppressWarnings("serial") 073 private static class MockMvcBuildException extends NestedRuntimeException { 074 075 public MockMvcBuildException(String msg, Throwable cause) { 076 super(msg, cause); 077 } 078 } 079 080}