org.springframework.mock.web.MockServletConfig Java Examples

The following examples show how to use org.springframework.mock.web.MockServletConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApiTestBase.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	M resource = createJaxRsResource();
	checkContextFields(resource);
	jaxRsResource = spy(resource);

	ConfigurationWarnings globalConfigWarnings = ConfigurationWarnings.getInstance();
	globalConfigWarnings.clear();

	MockServletContext servletContext = new MockServletContext();
	MockServletConfig servletConfig = new MockServletConfig(servletContext, "JAX-RS-MockDispatcher");
	jaxRsResource.servletConfig = servletConfig;
	IbisContext ibisContext = mock(IbisContext.class);
	IbisManager ibisManager = new MockIbisManager();
	ibisManager.setIbisContext(ibisContext);
	MessageKeeper messageKeeper = new MessageKeeper();
	doReturn(messageKeeper).when(ibisContext).getMessageKeeper();
	doReturn(ibisManager).when(ibisContext).getIbisManager();
	doReturn(ibisContext).when(jaxRsResource).getIbisContext();

	dispatcher.register(jaxRsResource);
}
 
Example #2
Source File: MockMvcBuilderSupport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig,
		WebApplicationContext webAppContext, RequestBuilder defaultRequestBuilder,
		List<ResultMatcher> globalResultMatchers, List<ResultHandler> globalResultHandlers,
		Boolean dispatchOptions) {

	ServletContext servletContext = webAppContext.getServletContext();

	TestDispatcherServlet dispatcherServlet = new TestDispatcherServlet(webAppContext);
	dispatcherServlet.setDispatchOptionsRequest(dispatchOptions);
	try {
		dispatcherServlet.init(servletConfig);
	}
	catch (ServletException ex) {
		// should never happen..
		throw new MockMvcBuildException("Failed to initialize TestDispatcherServlet", ex);
	}

	MockMvc mockMvc = new MockMvc(dispatcherServlet, filters, servletContext);
	mockMvc.setDefaultRequest(defaultRequestBuilder);
	mockMvc.setGlobalResultMatchers(globalResultMatchers);
	mockMvc.setGlobalResultHandlers(globalResultHandlers);

	return mockMvc;
}
 
Example #3
Source File: DispatcherServletChannelInitializer.java    From nettyholdspringmvc with Apache License 2.0 6 votes vote down vote up
public DispatcherServletChannelInitializer() throws ServletException {

    	MockServletContext servletContext = new MockServletContext();
    	MockServletConfig servletConfig = new MockServletConfig(servletContext);
        servletConfig.addInitParameter("contextConfigLocation","classpath:/META-INF/spring/root-context.xml");
        servletContext.addInitParameter("contextConfigLocation","classpath:/META-INF/spring/root-context.xml");

    	//AnnotationConfigWebApplicationContext wac = new AnnotationConfigWebApplicationContext();
        XmlWebApplicationContext wac = new XmlWebApplicationContext();

        //ClassPathXmlApplicationContext wac = new ClassPathXmlApplicationContext();
		wac.setServletContext(servletContext);
		wac.setServletConfig(servletConfig);
        wac.setConfigLocation("classpath:/servlet-context.xml");
    	//wac.register(WebConfig.class);
    	wac.refresh();

    	this.dispatcherServlet = new DispatcherServlet(wac);
    	this.dispatcherServlet.init(servletConfig);
	}
 
Example #4
Source File: AbstractTestExecutorService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected TemplateModel createModel(ObjectWrapper wrapper) throws Throwable {
	HttpServletRequest request = super.getRequestContext().getRequest();
	HttpServletResponse response = super.getRequestContext().getResponse();
	ServletContext servletContext = request.getSession().getServletContext();
	AllHttpScopesHashModel hashModel = new AllHttpScopesHashModel(wrapper, servletContext, request); //super.createModel(wrapper, servletContext, request, response);
	ControllerServlet servlet = new ControllerServlet();
	MockServletConfig config = new MockServletConfig(servletContext);
	servlet.init(config);
	ServletContextHashModel newServletContextModel = new ServletContextHashModel(servlet, wrapper);
	ServletContextHashModel servletContextModel = new ServletContextHashModel(servlet, wrapper);
	servletContext.setAttribute(ATTR_APPLICATION_MODEL, servletContextModel);
	TaglibFactory taglibs = new TaglibFactory(servletContext);
	servletContext.setAttribute(ATTR_JSP_TAGLIBS_MODEL, taglibs);
	hashModel.putUnlistedModel(FreemarkerServlet.KEY_APPLICATION, newServletContextModel);
	hashModel.putUnlistedModel(FreemarkerServlet.KEY_APPLICATION_PRIVATE, newServletContextModel);
	hashModel.putUnlistedModel(FreemarkerServlet.KEY_JSP_TAGLIBS, taglibs);
	HttpRequestHashModel requestModel = new HttpRequestHashModel(request, response, wrapper);
       request.setAttribute(ATTR_REQUEST_MODEL, requestModel);
	hashModel.putUnlistedModel(FreemarkerServlet.KEY_REQUEST_PRIVATE, requestModel);
	return hashModel;
}
 
Example #5
Source File: SpringWebMvc_5_x_IT.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequest() throws Exception {
    MockServletConfig config = new MockServletConfig();
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();

    config.addInitParameter("contextConfigLocation", "classpath:spring-web-test.xml");
    req.setMethod("GET");
    req.setRequestURI("/");
    req.setRemoteAddr("1.2.3.4");
    
    DispatcherServlet servlet = new DispatcherServlet();
    servlet.init(config);
    
    servlet.service(req, res);
    
    Method method = FrameworkServlet.class.getDeclaredMethod("doGet", HttpServletRequest.class, HttpServletResponse.class);
    
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    
    verifier.verifyTrace(Expectations.event(SPRING_MVC, method));
    verifier.verifyTraceCount(0);
}
 
Example #6
Source File: SpringWebMvc_3_x_to_4_x_IT.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequest() throws Exception {
    MockServletConfig config = new MockServletConfig();
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();

    config.addInitParameter("contextConfigLocation", "classpath:spring-web-test.xml");
    req.setMethod("GET");
    req.setRequestURI("/");
    req.setRemoteAddr("1.2.3.4");
    
    DispatcherServlet servlet = new DispatcherServlet();
    servlet.init(config);
    
    servlet.service(req, res);
    
    Method method = FrameworkServlet.class.getDeclaredMethod("doGet", HttpServletRequest.class, HttpServletResponse.class);
    
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    
    verifier.verifyTrace(Expectations.event(SPRING_MVC, method));
    verifier.verifyTraceCount(0);
}
 
Example #7
Source File: AbstractRepositoryServletTestCase.java    From archiva with Apache License 2.0 6 votes vote down vote up
protected void startRepository()
    throws Exception
{

    final MockServletContext mockServletContext = new MockServletContext();

    WebApplicationContext webApplicationContext =
        new TestWebapplicationContext( applicationContext, mockServletContext );

    mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                                     webApplicationContext );

    MockServletConfig mockServletConfig = new MockServletConfig()
    {
        @Override
        public ServletContext getServletContext()
        {
            return mockServletContext;
        }
    };

    unauthenticatedRepositoryServlet.init( mockServletConfig );

}
 
Example #8
Source File: MockMvcBuilderSupport.java    From java-technology-stack with MIT License 6 votes vote down vote up
protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig,
		WebApplicationContext webAppContext, @Nullable RequestBuilder defaultRequestBuilder,
		List<ResultMatcher> globalResultMatchers, List<ResultHandler> globalResultHandlers,
		@Nullable List<DispatcherServletCustomizer> dispatcherServletCustomizers) {

	TestDispatcherServlet dispatcherServlet = new TestDispatcherServlet(webAppContext);
	if (dispatcherServletCustomizers != null) {
		for (DispatcherServletCustomizer customizers : dispatcherServletCustomizers) {
			customizers.customize(dispatcherServlet);
		}
	}
	try {
		dispatcherServlet.init(servletConfig);
	}
	catch (ServletException ex) {
		// should never happen..
		throw new MockMvcBuildException("Failed to initialize TestDispatcherServlet", ex);
	}

	MockMvc mockMvc = new MockMvc(dispatcherServlet, filters);
	mockMvc.setDefaultRequest(defaultRequestBuilder);
	mockMvc.setGlobalResultMatchers(globalResultMatchers);
	mockMvc.setGlobalResultHandlers(globalResultHandlers);

	return mockMvc;
}
 
Example #9
Source File: AbstractMockMvcBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Build a {@link org.springframework.test.web.servlet.MockMvc} instance.
 */
@Override
@SuppressWarnings("rawtypes")
public final MockMvc build() {
	WebApplicationContext wac = initWebAppContext();
	ServletContext servletContext = wac.getServletContext();
	MockServletConfig mockServletConfig = new MockServletConfig(servletContext);

	for (MockMvcConfigurer configurer : this.configurers) {
		RequestPostProcessor processor = configurer.beforeMockMvcCreated(this, wac);
		if (processor != null) {
			if (this.defaultRequestBuilder == null) {
				this.defaultRequestBuilder = MockMvcRequestBuilders.get("/");
			}
			if (this.defaultRequestBuilder instanceof ConfigurableSmartRequestBuilder) {
				((ConfigurableSmartRequestBuilder) this.defaultRequestBuilder).with(processor);
			}
		}
	}

	Filter[] filterArray = this.filters.toArray(new Filter[0]);

	return super.createMockMvc(filterArray, mockServletConfig, wac, this.defaultRequestBuilder,
			this.globalResultMatchers, this.globalResultHandlers, this.dispatcherServletCustomizers);
}
 
Example #10
Source File: MockTdsContextLoader.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public ApplicationContext loadContext(String... locations) throws Exception {
  final MockServletContext servletContext = new MockTdsServletContext();
  final MockServletConfig servletConfig = new MockServletConfig(servletContext);
  final XmlWebApplicationContext webApplicationContext = new XmlWebApplicationContext();

  servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
  webApplicationContext.setServletConfig(servletConfig);
  webApplicationContext.setConfigLocations(locations);
  webApplicationContext.refresh();

  TdsContext tdsContext = webApplicationContext.getBean(TdsContext.class);
  checkContentRootPath(webApplicationContext, tdsContext);

  webApplicationContext.registerShutdownHook();

  return webApplicationContext;
}
 
Example #11
Source File: MockMvcBuilderSupport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig,
		WebApplicationContext webAppContext, @Nullable RequestBuilder defaultRequestBuilder,
		List<ResultMatcher> globalResultMatchers, List<ResultHandler> globalResultHandlers,
		@Nullable List<DispatcherServletCustomizer> dispatcherServletCustomizers) {

	TestDispatcherServlet dispatcherServlet = new TestDispatcherServlet(webAppContext);
	if (dispatcherServletCustomizers != null) {
		for (DispatcherServletCustomizer customizers : dispatcherServletCustomizers) {
			customizers.customize(dispatcherServlet);
		}
	}
	try {
		dispatcherServlet.init(servletConfig);
	}
	catch (ServletException ex) {
		// should never happen..
		throw new MockMvcBuildException("Failed to initialize TestDispatcherServlet", ex);
	}

	MockMvc mockMvc = new MockMvc(dispatcherServlet, filters);
	mockMvc.setDefaultRequest(defaultRequestBuilder);
	mockMvc.setGlobalResultMatchers(globalResultMatchers);
	mockMvc.setGlobalResultHandlers(globalResultHandlers);

	return mockMvc;
}
 
Example #12
Source File: AbstractMockMvcBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Build a {@link org.springframework.test.web.servlet.MockMvc} instance.
 */
@Override
@SuppressWarnings("rawtypes")
public final MockMvc build() {
	WebApplicationContext wac = initWebAppContext();
	ServletContext servletContext = wac.getServletContext();
	MockServletConfig mockServletConfig = new MockServletConfig(servletContext);

	for (MockMvcConfigurer configurer : this.configurers) {
		RequestPostProcessor processor = configurer.beforeMockMvcCreated(this, wac);
		if (processor != null) {
			if (this.defaultRequestBuilder == null) {
				this.defaultRequestBuilder = MockMvcRequestBuilders.get("/");
			}
			if (this.defaultRequestBuilder instanceof ConfigurableSmartRequestBuilder) {
				((ConfigurableSmartRequestBuilder) this.defaultRequestBuilder).with(processor);
			}
		}
	}

	Filter[] filterArray = this.filters.toArray(new Filter[0]);

	return super.createMockMvc(filterArray, mockServletConfig, wac, this.defaultRequestBuilder,
			this.globalResultMatchers, this.globalResultHandlers, this.dispatcherServletCustomizers);
}
 
Example #13
Source File: RssFeedServletTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp()
    throws Exception
{
    final MockServletContext mockServletContext = new MockServletContext();

    WebApplicationContext webApplicationContext =
        new TestWebapplicationContext( applicationContext, mockServletContext );

    mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                                     webApplicationContext );

    MockServletConfig mockServletConfig = new MockServletConfig()
    {
        @Override
        public ServletContext getServletContext()
        {
            return mockServletContext;
        }
    };

    repositoryRegistry.reload();
    repositoryRegistry.putRepository( new BasicManagedRepository( "internal", "internal",
        new FilesystemStorage( Paths.get( "target/appserver-base/repositories/internal" ), new DefaultFileLockManager( ) ) ) );
    rssFeedServlet.init( mockServletConfig );
}
 
Example #14
Source File: DelegatingServletTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDelegateToTheGivenServlet() throws IOException, ServletException {
    MockServletContext ctx = new MockServletContext();
    ctx.addInitParameter(DelegatingListener.DELEGATE_SERVLET, DummyServlet.class.getCanonicalName());
    ServletContextEvent evt = new ServletContextEvent(ctx);
    DelegatingListener listener = new DelegatingListener();
    listener.contextInitialized(evt);
    assertThat((DummyServlet) ctx.getAttribute(DelegatingListener.DELEGATE_SERVLET), isA(DummyServlet.class));
    DelegatingServlet servlet = new DelegatingServlet();
    servlet.init(new MockServletConfig(ctx));

    servlet.service(httpServletRequest, new MockHttpServletResponse());
    verify(servletRequestWrapper).setRequestURI("/go/stuff/action");
}
 
Example #15
Source File: ApiListenerServletTest.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws ServletException {
	servlet = spy(ApiListenerServlet.class);
	ServletConfig servletConfig = new MockServletConfig();
	when(servlet.getServletConfig()).thenReturn(servletConfig);
	servlet.init();

	session = null;
}
 
Example #16
Source File: AdminJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test of getAdminPagePreview method, of class fr.paris.lutece.portal.web.admin.AdminJspBean.
 * 
 * @throws UserNotSignedException
 */
public void testGetAdminPagePreview( ) throws AccessDeniedException, UserNotSignedException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );

    // FIXME : MokeHttpServletRequest should be fixed to support attributes
    Map<String, Right> mapRights = new HashMap<>( );
    Right right = new Right( );
    right.setId( AdminPageJspBean.RIGHT_MANAGE_ADMIN_SITE );
    mapRights.put( AdminPageJspBean.RIGHT_MANAGE_ADMIN_SITE, right );
    AdminUser user = new AdminUser( );
    user.setRights( mapRights );
    user.setLocale( new Locale( "fr", "FR", "" ) );
    request.getSession( true ).setAttribute( ATTRIBUTE_ADMIN_USER, user );
    LocalVariables.setLocal( new MockServletConfig( ), request, new MockHttpServletResponse( ) );

    AdminPageJspBean instance = new AdminPageJspBean( );
    instance.init( request, AdminPageJspBean.RIGHT_MANAGE_ADMIN_SITE );

    try
    {
        instance.getAdminPagePreview( request );
    }
    catch( SiteMessageException e )
    {
        fail( );
    }
}
 
Example #17
Source File: PortalJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test of getContent method, of class fr.paris.lutece.portal.web.PortalJspBean.
 */
public void testGetContent( ) throws Exception
{
    HttpServletRequest request = new MockHttpServletRequest( );
    LocalVariables.setLocal( new MockServletConfig( ), request, new MockHttpServletResponse( ) );
    PortalJspBean instance = new PortalJspBean( );

    String result = instance.getContent( request );
    assertTrue( StringUtils.isNotEmpty( result ) );
}
 
Example #18
Source File: DispatcherServletChannelInitializer.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public DispatcherServletChannelInitializer(Class<? extends WebMvcConfigurerAdapter> clasConfig) throws ServletException {
	MockServletContext servletContext = new MockServletContext();
	MockServletConfig servletConfig = new MockServletConfig(servletContext);

	//the alternative for web.xml
	AnnotationConfigWebApplicationContext wac = new AnnotationConfigWebApplicationContext();
	wac.setServletContext(servletContext);
	wac.setServletConfig(servletConfig);
	wac.register(clasConfig);
	wac.refresh();

	this.dispatcherServlet = new DispatcherServlet(wac);
	this.dispatcherServlet.init(servletConfig);
}
 
Example #19
Source File: BaseMockServletTestCase.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
* 
* @throws Exception - if something is wrong this exception is thrown.
*/
 @Before
 public void setUp() throws Exception {
     securityManager = new MockSecurityManager();
     servletContext = new MockServletContext();
     servletConfig = new MockServletConfig(servletContext);
 }
 
Example #20
Source File: ServletUrlProviderTest.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception {
	katharsisServlet = new KatharsisServlet();

	servletContext = new MockServletContext();
	((MockServletContext) servletContext).setContextPath("");
	servletConfig = new MockServletConfig(servletContext);
	((MockServletConfig) servletConfig).addInitParameter(KatharsisProperties.RESOURCE_SEARCH_PACKAGE, RESOURCE_SEARCH_PACKAGE);

	katharsisServlet.init(servletConfig);
	nodeRepository = new NodeRepository();
}
 
Example #21
Source File: EndpointsServletTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void contentLengthHeaderPresent() throws IOException, ServletException {
  MockServletConfig config = new MockServletConfig();
  config.addInitParameter("services", TestApi.class.getName());
  config.addInitParameter("addContentLength", "true");
  servlet.init(config);

  req.setRequestURI("/_ah/api/test/v2/echo");
  req.setMethod("POST");
  req.setParameter("x", "1");

  servlet.service(req, resp);

  assertThat(resp.getHeader("Content-Length")).isNotNull();
}
 
Example #22
Source File: EndpointsServletTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws ServletException {
  req = new MockHttpServletRequest();
  req.setServletPath("/_ah/api");
  req.addHeader("Host", API_SERVER_NAME);
  req.setServerName(API_SERVER_NAME);
  req.setServerPort(API_PORT);
  resp = new MockHttpServletResponse();
  servlet = new EndpointsServlet();
  MockServletConfig config = new MockServletConfig();
  config.addInitParameter("services", TestApi.class.getName());
  servlet.init(config);
}
 
Example #23
Source File: SampleKatharsisServletTest.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception {
	katharsisServlet = new SampleKatharsisServlet();

	servletContext = new MockServletContext();
	((MockServletContext) servletContext).setContextPath("");
	servletConfig = new MockServletConfig(servletContext);
	((MockServletConfig) servletConfig).addInitParameter(KatharsisProperties.RESOURCE_SEARCH_PACKAGE,
			RESOURCE_SEARCH_PACKAGE);
	((MockServletConfig) servletConfig).addInitParameter(KatharsisProperties.RESOURCE_DEFAULT_DOMAIN,
			RESOURCE_DEFAULT_DOMAIN);

	katharsisServlet.init(servletConfig);
	nodeRepository = new NodeRepository();
}
 
Example #24
Source File: SafeDispatcherServletTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

    this.safeServlet = new SafeDispatcherServlet();

    this.mockContext = new MockServletContext();
    this.mockConfig = new MockServletConfig(this.mockContext);
}
 
Example #25
Source File: CrnkServletRejectJsonTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception {
    servlet = new CrnkServlet();
    servlet.getBoot().addModule(new ServletTestModule());

    servletContext = new MockServletContext();
    ((MockServletContext) servletContext).setContextPath("");
    MockServletConfig servletConfig = new MockServletConfig(servletContext);
    servletConfig
            .addInitParameter(CrnkProperties.RESOURCE_DEFAULT_DOMAIN, RESOURCE_DEFAULT_DOMAIN);
    servletConfig
            .addInitParameter(CrnkProperties.REJECT_PLAIN_JSON, String.valueOf(true));

    servlet.init(servletConfig);
}
 
Example #26
Source File: CrnkServletTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception {
    servlet = new CrnkServlet();
    servlet.getBoot().addModule(new ServletTestModule());

    servletContext = new MockServletContext();
    ((MockServletContext) servletContext).setContextPath("");
    servletConfig = new MockServletConfig(servletContext);
    ((MockServletConfig) servletConfig)
            .addInitParameter(CrnkProperties.RESOURCE_DEFAULT_DOMAIN, RESOURCE_DEFAULT_DOMAIN);

    servlet.init(servletConfig);
}
 
Example #27
Source File: OpenTracingServerModuleTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private void initModule() throws ServletException {
	OpenTracingServerModule module = new OpenTracingServerModule(tracer);
	module.setUseSimpleTransactionNames(simpleTransactionNames);

	servlet = new CrnkServlet();
	CrnkBoot boot = servlet.getBoot();
	boot.addModule(new TestModule());
	boot.addModule(module);
	servlet.init(new MockServletConfig());
}
 
Example #28
Source File: MockJerseyServlet.java    From karate with MIT License 5 votes vote down vote up
/**
 * this zero-arg constructor will be invoked if you use the 'configure
 * httpClientClass' option refer to the MockJerseyServletFactory for how you
 * can construct this manually and have full control over
 * dependency-injection specific to your environment
 *
 * @throws Exception
 */
public MockJerseyServlet() throws Exception {
    logger.info("auto construction of mock http servlet");
    ServletConfig servletConfig = new MockServletConfig();
    servletContext = new MockServletContext();
    ResourceConfig resourceConfig = new ResourceConfig(HelloResource.class);
    servlet = new ServletContainer(resourceConfig);
    servlet.init(servletConfig);
}
 
Example #29
Source File: MockSpringMvcServlet.java    From karate with MIT License 5 votes vote down vote up
private static Servlet initServlet() {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(MockDemoConfig.class);
    context.setServletContext(SERVLET_CONTEXT);
    DispatcherServlet servlet = new DispatcherServlet(context);
    ServletConfig servletConfig = new MockServletConfig();
    try {
        servlet.init(servletConfig);
        customize(servlet);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return servlet;
}
 
Example #30
Source File: AbstractMockMvcBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Build a {@link org.springframework.test.web.servlet.MockMvc} instance.
 */
@Override
@SuppressWarnings("rawtypes")
public final MockMvc build() {

	WebApplicationContext wac = initWebAppContext();

	ServletContext servletContext = wac.getServletContext();
	MockServletConfig mockServletConfig = new MockServletConfig(servletContext);

	for (MockMvcConfigurer configurer : this.configurers) {
		RequestPostProcessor processor = configurer.beforeMockMvcCreated(this, wac);
		if (processor != null) {
			if (this.defaultRequestBuilder == null) {
				this.defaultRequestBuilder = MockMvcRequestBuilders.get("/");
			}
			if (this.defaultRequestBuilder instanceof ConfigurableSmartRequestBuilder) {
				((ConfigurableSmartRequestBuilder) this.defaultRequestBuilder).with(processor);
			}
		}
	}

	Filter[] filterArray = this.filters.toArray(new Filter[this.filters.size()]);

	return super.createMockMvc(filterArray, mockServletConfig, wac, this.defaultRequestBuilder,
			this.globalResultMatchers, this.globalResultHandlers, this.dispatchOptions);
}