Java Code Examples for org.springframework.mock.web.MockServletContext

The following examples show how to use org.springframework.mock.web.MockServletContext. These examples are extracted from open source projects. 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
@Before
public void setup() throws ServletException {
	simpleTransactionNames = false;

	tracer = Mockito.mock(Tracer.class);
	MockServletContext servletContext = new MockServletContext();

	initModule();

	request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setContextPath("");
	request.setServletPath("/api");
	request.setPathInfo("/tasks/");
	request.setRequestURI("/api/tasks/");
	request.setContentType(HttpHeaders.JSONAPI_CONTENT_TYPE);
	request.addHeader("Accept", "*/*");
}
 
Example 2
@Before
public void setUp() {
	ServletContext servletContext = new MockServletContext();
	MockHttpServletRequest mockRequest = new MockHttpServletRequest(servletContext);
	mockRequest.setAttribute(FROM_CUSTOM_MOCK, FROM_CUSTOM_MOCK);
	RequestContextHolder.setRequestAttributes(new ServletWebRequest(mockRequest, new MockHttpServletResponse()));

	this.wac.setServletContext(servletContext);
	new AnnotatedBeanDefinitionReader(this.wac).register(WebConfig.class);
	this.wac.refresh();

	this.mockMvc = webAppContextSetup(this.wac)
			.defaultRequest(get("/").requestAttr(FROM_MVC_TEST_DEFAULT, FROM_MVC_TEST_DEFAULT))
			.alwaysExpect(status().isOk())
			.build();
}
 
Example 3
@Test
public void verifyBadUsername() throws Exception {
    final MockRequestContext context = new MockRequestContext();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter(OpenIdConstants.OPENID_IDENTITY, "fablah");
    request.setParameter(OpenIdConstants.OPENID_RETURNTO, "http://www.cnn.com");

    final OpenIdService service = OpenIdService.createServiceFrom(request, null);
    context.getFlowScope().put("service", service);
    context.getFlowScope().put("ticketGrantingTicketId", "tgtId");

    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request,
            new MockHttpServletResponse()));
    assertEquals("error", this.action.execute(context).getId());
}
 
Example 4
@Test
public void testRenewWithServiceAndSameCredentials() throws Exception {
    final String ticketGrantingTicket = getCentralAuthenticationService()
        .createTicketGrantingTicket(
            TestUtils.getCredentialsWithSameUsernameAndPassword());
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    context.getFlowScope().put("ticketGrantingTicketId", ticketGrantingTicket);
    request.addParameter("renew", "true");
    request.addParameter("service", "test");
    request.addParameter("username", "test");
    request.addParameter("password", "test");

    context.setExternalContext(new ServletExternalContext(
        new MockServletContext(), request, new MockHttpServletResponse()));
    context.getFlowScope().put("service", TestUtils.getService("test"));
//    this.action.bind(context);
 //   assertEquals("warn", this.action.submit(context).getId());
}
 
Example 5
@Test
public void verifySsoSessionCookieOnRenewAsParameter() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter(CasProtocolConstants.PARAMETER_RENEW, "true");

    final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
    when(tgt.getId()).thenReturn("test");
    request.setCookies(new Cookie("TGT", "test5"));
    WebUtils.putTicketGrantingTicketInScopes(this.context, tgt);
    this.context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));

    this.action.setCreateSsoSessionCookieOnRenewAuthentications(false);
    assertEquals("success", this.action.execute(this.context).getId());
    assertEquals(0, response.getCookies().length);
}
 
Example 6
Source Project: cas4.0.x-server-wechat   Source File: WiringTests.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    applicationContext = new XmlWebApplicationContext();
    applicationContext.setConfigLocations(new String[]{
            "file:src/main/webapp/WEB-INF/cas-management-servlet.xml",
            "file:src/main/webapp/WEB-INF/managementConfigContext.xml",
    "file:src/main/webapp/WEB-INF/spring-configuration/*.xml"});
    applicationContext.setServletContext(new MockServletContext(new ResourceLoader() {
        @Override
        public Resource getResource(final String location) {
            return new FileSystemResource("src/main/webapp" + location);
        }

        @Override
        public ClassLoader getClassLoader() {
            return getClassLoader();
        }
    }));
    applicationContext.refresh();
}
 
Example 7
@Test
public void verifyTgtToSetRemovingOldTgt() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockHttpServletRequest request = new MockHttpServletRequest();

    final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
    when(tgt.getId()).thenReturn("test");

    request.setCookies(new Cookie("TGT", "test5"));
    WebUtils.putTicketGrantingTicketInScopes(this.context, tgt);
    this.context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));

    assertEquals("success", this.action.execute(this.context).getId());
    request.setCookies(response.getCookies());
    assertEquals(tgt.getId(), this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request));
}
 
Example 8
@Test
public void verifyTicketGrantingTicketNotTgtButGateway() throws Exception {
    final MockRequestContext context = new MockRequestContext();
    context.getFlowScope().put("service", TestUtils.getService());
    final MockHttpServletRequest request = new MockHttpServletRequest();
    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));
    request.addParameter("service", "service");
    request.addParameter("gateway", "true");
    final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
    when(tgt.getId()).thenReturn("bleh");
    WebUtils.putTicketGrantingTicketInScopes(context, tgt);


    assertEquals("gateway", this.action.execute(context).getId());
}
 
Example 9
@Test
public void ensureLdapAttributeShouldDoSpnego() {
    final LdapSpnegoKnownClientSystemsFilterAction action =
            new LdapSpnegoKnownClientSystemsFilterAction(this.connectionFactory,
            this.searchRequest, "mail");
    final MockRequestContext ctx = new MockRequestContext();
    final MockHttpServletRequest req = new MockHttpServletRequest();
    req.setRemoteAddr("localhost");
    final ServletExternalContext extCtx = new ServletExternalContext(
            new MockServletContext(), req,
            new MockHttpServletResponse());
    ctx.setExternalContext(extCtx);

    final Event ev = action.doExecute(ctx);
    assertEquals(ev.getId(), new EventFactorySupport().yes(this).getId());
}
 
Example 10
@Test
public void testIncludeServletPath() throws ServletException, IOException {
	// create an empty mock context
	MockServletContext context = new TestServletContext(true);
	MockHttpServletRequest request = new MockHttpServletRequest(context);
	request.setServletPath("/org");
	request.setPathInfo("/geomajas/servlet/test.js");
	request.setMethod("GET");
	MockHttpServletResponse response = new MockHttpServletResponse();
	ResourceController resourceController = new ResourceController();
	resourceController.setIncludeServletPath(true);
	resourceController.setServletContext(context);
	resourceController.getResource(request, response);
	Resource resource = new ClassPathResource("/org/geomajas/servlet/test.js");
	Assert.assertArrayEquals(IOUtils.toByteArray(resource.getInputStream()), response.getContentAsByteArray());
}
 
Example 11
@Test
public void testServiceTicketFromCookie() throws Exception {
    MockRequestContext context = new MockRequestContext();
    context.getFlowScope().put("service", TestUtils.getService());
    context.getFlowScope().put("ticketGrantingTicketId", this.ticketGrantingTicket);
    MockHttpServletRequest request = new MockHttpServletRequest();
    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));
    request.addParameter("service", "service");
    request.setCookies(new Cookie[] {new Cookie("TGT",
            this.ticketGrantingTicket)});

    this.action.execute(context);

    assertNotNull(WebUtils.getServiceTicketFromRequestScope(context));
}
 
Example 12
Source Project: cas4.0.x-server-wechat   Source File: WiringTests.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    applicationContext = new XmlWebApplicationContext();
    applicationContext.setConfigLocations(new String[]{
            "file:src/main/webapp/WEB-INF/cas-servlet.xml",
            "file:src/main/webapp/WEB-INF/deployerConfigContext.xml",
    "file:src/main/webapp/WEB-INF/spring-configuration/*.xml"});
    applicationContext.setServletContext(new MockServletContext(new ResourceLoader() {
        @Override
        public Resource getResource(final String location) {
            return new FileSystemResource("src/main/webapp" + location);
        }

        @Override
        public ClassLoader getClassLoader() {
            return getClassLoader();
        }
    }));
    applicationContext.refresh();
}
 
Example 13
@Test
    public void testSuccessfulAuthenticationWithNoServiceAndWarn()
        throws Exception {
        final MockHttpServletRequest request = new MockHttpServletRequest();
        final MockHttpServletResponse response = new MockHttpServletResponse();
        final MockRequestContext context = new MockRequestContext();

        request.addParameter("username", "test");
        request.addParameter("password", "test");
        request.addParameter("warn", "true");

        context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, response));
        context.getRequestScope().put("credentials",
            TestUtils.getCredentialsWithSameUsernameAndPassword());
  //      this.action.bind(context);
   //     assertEquals("success", this.action.submit(context).getId());
//        assertNotNull(response.getCookie(this.warnCookieGenerator
//            .getCookieName()));
    }
 
Example 14
@Test
public void initialize_test() {
    Injector injector = Guice.createInjector(createNiceMock(Module.class));

    MockServletContext mockServletContext = new MockServletContext();
    mockServletContext.addInitParameter("contextConfigLocation",
            "classpath:rave-shindig-test-applicationContext.xml, classpath:rave-shindig-test-dataContext.xml");
    mockServletContext.setAttribute(GuiceServletContextListener.INJECTOR_ATTRIBUTE, injector);

    GuiceBindingSpringContextLoaderListener listener = new GuiceBindingSpringContextLoaderListener();
    ServletContextEvent event = createNiceMock(ServletContextEvent.class);
    expect(event.getServletContext()).andReturn(mockServletContext).anyTimes();
    replay(event);

    listener.contextInitialized(event);
    assertThat((Injector)mockServletContext.getAttribute(GuiceServletContextListener.INJECTOR_ATTRIBUTE), is(not(sameInstance(injector))));

}
 
Example 15
@Test
 public void testRenewWithServiceAndBadCredentials() throws Exception {
     final String ticketGrantingTicket = getCentralAuthenticationService()
         .createTicketGrantingTicket(
             TestUtils.getCredentialsWithSameUsernameAndPassword());
     final MockHttpServletRequest request = new MockHttpServletRequest();
     final MockRequestContext context = new MockRequestContext();

     context.getFlowScope().put("ticketGrantingTicketId", ticketGrantingTicket);
     request.addParameter("renew", "true");
     request.addParameter("service", "test");

     context.setExternalContext(new ServletExternalContext(
         new MockServletContext(), request, new MockHttpServletResponse()));
     context.getRequestScope().put("credentials",
         TestUtils.getCredentialsWithDifferentUsernameAndPassword());
     context.getRequestScope().put(
         "org.springframework.validation.BindException.credentials",
         new BindException(TestUtils
             .getCredentialsWithDifferentUsernameAndPassword(),
             "credentials"));
//     this.action.bind(context);
//     assertEquals("error", this.action.submit(context).getId());
 }
 
Example 16
@Test
public void testRenewWithServiceAndDifferentCredentials() throws Exception {
    final String ticketGrantingTicket = getCentralAuthenticationService()
        .createTicketGrantingTicket(
            TestUtils.getCredentialsWithSameUsernameAndPassword());
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    context.getFlowScope().put("ticketGrantingTicketId", ticketGrantingTicket);
    request.addParameter("renew", "true");
    request.addParameter("service", "test");
    request.addParameter("username", "test2");
    request.addParameter("password", "test2");

    context.setExternalContext(new ServletExternalContext(
        new MockServletContext(), request, new MockHttpServletResponse()));
//    this.action.bind(context);

//    assertEquals("success", this.action.submit(context).getId());
}
 
Example 17
@Test
    public void testFailedAuthenticationWithNoService() throws Exception {
        final MockHttpServletRequest request = new MockHttpServletRequest();
        final MockRequestContext context = new MockRequestContext();

        request.addParameter("username", "test");
        request.addParameter("password", "test2");

        context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));

        context.getRequestScope().put("credentials",
            TestUtils.getCredentialsWithDifferentUsernameAndPassword());
        context.getRequestScope().put(
            "org.springframework.validation.BindException.credentials",
            new BindException(TestUtils
                .getCredentialsWithDifferentUsernameAndPassword(),
                "credentials"));

    //    this.action.bind(context);
//        assertEquals("error", this.action.submit(context).getId());
    }
 
Example 18
@Test
public void verifySuccessfulAuthenticationWithNoService() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    WebUtils.putLoginTicket(context, "LOGIN");
    request.addParameter("lt", "LOGIN");
    request.addParameter("username", "test");
    request.addParameter("password", "test");

    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    putCredentialInRequestScope(context, c);

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("success", this.action.submit(context, c, messageContext).getId());
}
 
Example 19
@Test
public void testServiceFound() throws Exception {
    final MockRequestContext context = new MockRequestContext();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("service", "test");
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));

    final Event event = this.action.execute(context);

    assertEquals("test", WebUtils.getService(context).getId());
    assertEquals("success", event.getId());
}
 
Example 20
@Before
public void setUp() throws Exception {

    MockServletContext sc = new MockServletContext();
    request = new MockHttpServletRequest(sc);
    webRequest = new ServletWebRequest(request);
    RequestContextHolder.setRequestAttributes(webRequest);
    request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
    factory = new DefaultDataBinderFactory(new ConfigurableWebBindingInitializer());
}
 
Example 21
@Test
public void verifyTgtToSet() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
    when(tgt.getId()).thenReturn("test");

    WebUtils.putTicketGrantingTicketInScopes(this.context, tgt);
    this.context.setExternalContext(new ServletExternalContext(new MockServletContext(),
            request, response));

    assertEquals("success", this.action.execute(this.context).getId());
    request.setCookies(response.getCookies());
    assertEquals(tgt.getId(), this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request));
}
 
Example 22
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 23
Source Project: tutorials   Source File: WebConfigurerUnitTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setup() {
    servletContext = spy(new MockServletContext());
    doReturn(mock(FilterRegistration.Dynamic.class))
        .when(servletContext).addFilter(anyString(), any(Filter.class));
    doReturn(mock(ServletRegistration.Dynamic.class))
        .when(servletContext).addServlet(anyString(), any(Servlet.class));

    env = new MockEnvironment();
    props = new JHipsterProperties();

    webConfigurer = new WebConfigurer(env, props);
}
 
Example 24
Source Project: hot-crawler   Source File: InfoControllerTest.java    License: MIT License 5 votes vote down vote up
@Test
public void verifyContext() {
    ServletContext servletContext = wac.getServletContext();

    org.junit.Assert.assertNotNull(servletContext);
    Assert.assertTrue(servletContext instanceof MockServletContext);
    Assert.assertNotNull(wac.getBean("InfoController"));
}
 
Example 25
Source Project: hot-crawler   Source File: AppTest.java    License: MIT License 5 votes vote down vote up
@Test
public void verifyContext() {
    ServletContext servletContext = wac.getServletContext();

    org.junit.Assert.assertNotNull(servletContext);
    Assert.assertTrue(servletContext instanceof MockServletContext);
    Assert.assertNotNull(wac.getBean("InfoController"));
}
 
Example 26
Source Project: sinavi-jfw   Source File: ViewIdOutTagTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {

    MockServletContext sc = new MockServletContext();
    req = new MockHttpServletRequest(sc);
    res = new MockHttpServletResponse();
    context = new MockPageContext(sc, req, res);
}
 
Example 27
@Test
public void verifyNoTgtToSet() throws Exception {
    this.context.setExternalContext(new ServletExternalContext(new MockServletContext(),
            new MockHttpServletRequest(), new MockHttpServletResponse()));

    assertEquals("success", this.action.execute(this.context).getId());
}
 
Example 28
Source Project: cas4.0.x-server-wechat   Source File: TestUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static MockRequestContext getContext(
    final MockHttpServletRequest request,
    final MockHttpServletResponse response) {
    final MockRequestContext context = new MockRequestContext();
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
    return context;
}
 
Example 29
Source Project: spring-cloud-sleuth   Source File: TraceFilterTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetTraceKeysForAnUntracedRequest() throws Exception {
	this.request = builder().param("foo", "bar")
			.buildRequest(new MockServletContext());
	this.response.setStatus(295);

	this.filter.doFilter(this.request, this.response, this.filterChain);

	then(Tracing.current().tracer().currentSpan()).isNull();
	then(this.spans).hasSize(1);
	then(this.spans.get(0).tags()).containsEntry("http.path", "/")
			.containsEntry("http.method", HttpMethod.GET.toString());
	// we don't check for status_code anymore cause Brave doesn't support it oob
	// .containsEntry("http.status_code", "295")
}
 
Example 30
@Test
public void testNoServiceFound() throws Exception {
    final MockRequestContext context = new MockRequestContext();
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), new MockHttpServletRequest(),
            new MockHttpServletResponse()));

    final Event event = this.action.execute(context);

    assertNull(WebUtils.getService(context));

    assertEquals("success", event.getId());
}