Example usage for org.springframework.mock.web MockHttpServletRequest setParameter

List of usage examples for org.springframework.mock.web MockHttpServletRequest setParameter

Introduction

In this page you can find the example usage for org.springframework.mock.web MockHttpServletRequest setParameter.

Prototype

public void setParameter(String name, String... values) 

Source Link

Document

Set an array of values for the specified HTTP parameter.

Usage

From source file:org.jasig.cas.support.oauth.web.OAuth20TokenAuthorizationCodeControllerTests.java

@Test
public void verifyWrongSecret() throws Exception {
    final AuthorizationCode authorizationCode = mock(AuthorizationCode.class);

    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, CLIENT_SECRET);

    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getToken(CODE, AuthorizationCode.class)).thenReturn(authorizationCode);
    when(centralOAuthService.getRegisteredService(CLIENT_ID)).thenReturn(service);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, WRONG_CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setCentralOAuthService(centralOAuthService);
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);//from  ww w . j a va  2s .  c o  m
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("application/json", mockResponse.getContentType());

    final ObjectMapper mapper = new ObjectMapper();

    final String expected = "{\"error\":\"" + OAuthConstants.INVALID_REQUEST + "\",\"error_description\":\""
            + OAuthConstants.INVALID_CLIENT_ID_OR_SECRET_DESCRIPTION + "\"}";
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText());
    assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText());
}

From source file:org.jasig.cas.support.oauth.web.OAuth20TokenAuthorizationCodeControllerTests.java

@Test
public void verifyRedirectUriDoesNotStartWithServiceId() throws Exception {
    final AuthorizationCode authorizationCode = mock(AuthorizationCode.class);

    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, CLIENT_SECRET);

    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getToken(CODE, AuthorizationCode.class)).thenReturn(authorizationCode);
    when(centralOAuthService.getRegisteredService(CLIENT_ID)).thenReturn(service);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, OTHER_REDIRECT_URI);

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setCentralOAuthService(centralOAuthService);
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);//from  w ww .  ja  va2s . c o m
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("application/json", mockResponse.getContentType());

    final ObjectMapper mapper = new ObjectMapper();

    final String expected = "{\"error\":\"" + OAuthConstants.INVALID_REQUEST + "\",\"error_description\":\""
            + OAuthConstants.INVALID_REDIRECT_URI_DESCRIPTION + "\"}";
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText());
    assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText());
}

From source file:org.jasig.cas.support.oauth.web.OAuth20TokenAuthorizationCodeControllerTests.java

@Test
public void verifyInvalidGrantType() throws Exception {
    final AuthorizationCode authorizationCode = mock(AuthorizationCode.class);
    when(authorizationCode.getType()).thenReturn(TokenType.PERSONAL);

    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, CLIENT_SECRET);

    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getToken(CODE, AuthorizationCode.class)).thenReturn(authorizationCode);
    when(centralOAuthService.getRegisteredService(CLIENT_ID)).thenReturn(service);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setCentralOAuthService(centralOAuthService);
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);/*from  w w  w. j  av  a2  s  . co  m*/
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("application/json", mockResponse.getContentType());

    final ObjectMapper mapper = new ObjectMapper();

    final String expected = "{\"error\":\"" + OAuthConstants.INVALID_GRANT + "\",\"error_description\":\""
            + OAuthConstants.INVALID_GRANT_TYPE_DESCRIPTION + "\"}";
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText());
    assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText());
}

From source file:com.programmingchronicles.tdd.web.addressbook.TestAddContactController.java

/**
 * Test de HttpPost: Verifica que el contacto se aade a la agenda
 * usando el servicio de address book.//w w w .  j a v a  2 s. co m
 *
 * <p><b>REFACTOFING:</b>
 *       El testDoPostGetParameters ya no era necesario, se prueba
 *       lo mismo en testDoPostAddContact. </p>
 *
 * <p>
 * El testDoPostAddContactRedirect tambin se ha fusionado aqui ya que tiene
 * ms sentido comprobar la funcionalidad completa.</p>
 */
@Test
public void testDoPostAddContact() throws ServletException, IOException, ParseException {
    // Fakes de los parametros del doGet y doPost que amplian la interfaz
    // estandar permitiendo verificaciones sencillas por estado.
    //
    // Se utilizan los mocks de Spring Test Utilities.
    MockHttpServletRequest fakeRequest = new MockHttpServletRequest();
    MockHttpServletResponse fakeResponse = new MockHttpServletResponse();

    // Ahora los fackes nos permiten configurar los parametros de entrada
    // del mtodo testeado. Esto no lo permitan los mocks del contenedor
    // ya que HttpServletRequest no tiene un "setParameters".
    fakeRequest.setParameter("firstName", "Pedro");
    fakeRequest.setParameter("surname", "Ballesteros");
    fakeRequest.setParameter("birthday", "8/1/1974");
    fakeRequest.setParameter("phone", "69696969");

    // Ejecucin del test.
    controller.doPost(fakeRequest, fakeResponse);

    // Verifica que se llama al addContact del mock del addressbook
    ArgumentCaptor<Contact> argument = ArgumentCaptor.forClass(Contact.class);
    verify(mockAddressbook).addContact(argument.capture());

    // En el verify anterior capturamos el argumento con el que se llama
    // a la agenda, y podemos validar que se aade el contacto correcto.
    Contact contact = argument.getValue();
    assertEquals("Pedro", contact.getFirstName());
    assertEquals("Ballesteros", contact.getSurname());
    assertEquals(dateFormat.parse("8/1/1974"), contact.getBirthday());
    assertEquals("69696969", contact.getPhone());

    // Verifica con el fake que no se ha intentado crear el modelo de errores
    assertNull(fakeRequest.getAttribute("errors"));

    // El Fake del HttpServletResponse ahora nos permite verificar por estado
    // la respuesta del doPost.

    // Verifica que se entrega un redirect de navegador al response, ahora
    // el fake nos permite acceder a datos de la respuesta.
    assertEquals("redirectPath", fakeResponse.getRedirectedUrl());
}

From source file:org.jasig.cas.support.oauth.web.OAuth20TokenAuthorizationCodeControllerTests.java

@Test
public void verifyOnlineOK() throws Exception {
    final ServiceTicket serviceTicket = mock(ServiceTicket.class);
    when(serviceTicket.getCreationTime()).thenReturn(new Date().getTime());

    final AuthorizationCode authorizationCode = mock(AuthorizationCode.class);
    when(authorizationCode.getTicket()).thenReturn(serviceTicket);
    when(authorizationCode.getType()).thenReturn(TokenType.ONLINE);

    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, CLIENT_SECRET);

    final AccessToken accessToken = mock(AccessToken.class);
    when(accessToken.getId()).thenReturn(AT_ID);
    when(accessToken.getTicket()).thenReturn(serviceTicket);

    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getToken(CODE, AuthorizationCode.class)).thenReturn(authorizationCode);
    when(centralOAuthService.getRegisteredService(CLIENT_ID)).thenReturn(service);
    when(centralOAuthService.grantOnlineAccessToken(authorizationCode)).thenReturn(accessToken);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setCentralOAuthService(centralOAuthService);
    oauth20WrapperController.setTimeout(TIMEOUT);
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);/*  ww w  .java  2s.c om*/
    assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
    assertEquals("application/json", mockResponse.getContentType());

    final ObjectMapper mapper = new ObjectMapper();
    final String expected = "{\"token_type\":\"" + OAuthConstants.BEARER_TOKEN + "\",\"expires_in\":\""
            + TIMEOUT + "\",\"access_token\":\"" + AT_ID + "\"}";
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("token_type").asText(), receivedObj.get("token_type").asText());
    assertTrue("received expires_at greater or equal to expected",
            expectedObj.get("expires_in").asInt() >= receivedObj.get("expires_in").asInt());
    assertEquals(expectedObj.get("access_token").asText(), receivedObj.get("access_token").asText());
}

From source file:org.jasig.cas.support.oauth.web.OAuth20TokenAuthorizationCodeControllerTests.java

@Test
public void verifyOfflineOK() throws Exception {
    final ServiceTicket serviceTicket = mock(ServiceTicket.class);
    when(serviceTicket.getCreationTime()).thenReturn(new Date().getTime());

    final AuthorizationCode authorizationCode = mock(AuthorizationCode.class);
    when(authorizationCode.getTicket()).thenReturn(serviceTicket);
    when(authorizationCode.getType()).thenReturn(TokenType.OFFLINE);

    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, CLIENT_SECRET);

    final RefreshToken refreshToken = mock(RefreshToken.class);
    when(refreshToken.getId()).thenReturn(RT_ID);

    final AccessToken accessToken = mock(AccessToken.class);
    when(accessToken.getId()).thenReturn(AT_ID);
    when(accessToken.getTicket()).thenReturn(serviceTicket);

    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getToken(CODE, AuthorizationCode.class)).thenReturn(authorizationCode);
    when(centralOAuthService.getRegisteredService(CLIENT_ID)).thenReturn(service);
    when(centralOAuthService.grantOfflineRefreshToken(authorizationCode, REDIRECT_URI))
            .thenReturn(refreshToken);/*from  ww  w . j  a  v  a  2s. co m*/
    when(centralOAuthService.grantOfflineAccessToken(refreshToken)).thenReturn(accessToken);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setCentralOAuthService(centralOAuthService);
    oauth20WrapperController.setTimeout(TIMEOUT);
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);
    assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
    assertEquals("application/json", mockResponse.getContentType());

    final ObjectMapper mapper = new ObjectMapper();
    final String expected = "{\"token_type\":\"" + OAuthConstants.BEARER_TOKEN + "\",\"expires_in\":\""
            + TIMEOUT + "\",\"refresh_token\":\"" + RT_ID + "\",\"access_token\":\"" + AT_ID + "\"}";
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("token_type").asText(), receivedObj.get("token_type").asText());
    assertTrue("received expires_at greater or equal to expected",
            expectedObj.get("expires_in").asInt() >= receivedObj.get("expires_in").asInt());
    assertEquals(expectedObj.get("refresh_token").asText(), receivedObj.get("refresh_token").asText());
    assertEquals(expectedObj.get("access_token").asText(), receivedObj.get("access_token").asText());
}

From source file:fragment.web.AuthenticationControllerTest.java

@Test
public void testLoginAfterLogout() throws Exception {
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/login");
    request.setParameter("logout", "");
    String actualResult = controller.login(request, map, new MockHttpSession());
    if (config.getAuthenticationService().compareToIgnoreCase("cas") == 0) {
        Assert.assertEquals("redirect:" + config.getCasLoginUrl() + "?service="
                + URLEncoder.encode(config.getCasServiceUrl(), "UTF-8"), actualResult);
    } else {//from   w w w  . j av a  2 s . c o m
        Assert.assertEquals("auth.login", actualResult);
    }
    boolean message = (Boolean) map.get("logout");
    Assert.assertTrue(message);
}

From source file:git.irbis.spring3.controllerusageexample.customers.web.ListCustomersControllerTest.java

/**
 * Test of request: show customers started from firstname, result success.
 *///w w w .j  a v a 2s  . co  m
@Test
public void testListCustomersByFirstNameSuccess() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    ListCustomersController listCustomersController = new ListCustomersController(
            new CustomerRepositoryMockImpl());
    request.setMethod("GET");
    request.setRequestURI("/listcustomers");
    request.setParameter("firstName", "first");
    request.setParameter("lastName", "");

    try {
        ModelAndView mv = new AnnotationMethodHandlerAdapter().handle(request, response,
                listCustomersController);

        ModelAndViewAssert.assertViewName(mv, "listcustomers");
        List<Customer> customers = (List<Customer>) mv.getModel().get("customers");

        assertNotNull(customers);
        assertEquals(5, customers.size());
    } catch (Exception ex) {
        fail();
    }
}

From source file:git.irbis.spring3.controllerusageexample.customers.web.ListCustomersControllerTest.java

/**
 * Test of request: show customer by fistname, result success.
 *//*from w w w  .ja  v a2 s. co m*/
@Test
public void testFindCustomerByFirstNameSuccess() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    ListCustomersController listCustomersController = new ListCustomersController(
            new CustomerRepositoryMockImpl());
    request.setMethod("GET");
    request.setRequestURI("/listcustomers");
    request.setParameter("firstName", "firstname1");
    request.setParameter("lastName", "");

    try {
        ModelAndView mv = new AnnotationMethodHandlerAdapter().handle(request, response,
                listCustomersController);

        ModelAndViewAssert.assertViewName(mv, "listcustomers");
        List<Customer> customers = (List<Customer>) mv.getModel().get("customers");

        assertNotNull(customers);
        assertEquals(1, customers.size());
    } catch (Exception ex) {
        fail();
    }
}

From source file:git.irbis.spring3.controllerusageexample.customers.web.ListCustomersControllerTest.java

/**
 * Test of request: show customers by firstname, result failure.
 *///w  w  w  .ja  v  a2 s.c om
@Test
public void testListCustomersByFirstNameFailure() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    ListCustomersController listCustomersController = new ListCustomersController(
            new CustomerRepositoryMockImpl());
    request.setMethod("GET");
    request.setRequestURI("/listcustomers");
    request.setParameter("firstName", "last");
    request.setParameter("lastName", "");

    try {
        ModelAndView mv = new AnnotationMethodHandlerAdapter().handle(request, response,
                listCustomersController);

        ModelAndViewAssert.assertViewName(mv, "listcustomers");
        List<Customer> customers = (List<Customer>) mv.getModel().get("customers");

        assertNotNull(customers);
        assertTrue(customers.isEmpty());
    } catch (Exception ex) {
        fail();
    }
}