org.springframework.mock.web.mockhttpservletrequest Java Examples

The following examples show how to use org.springframework.mock.web.mockhttpservletrequest. 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: AttributeJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void testDoModifyAttribute( AttributeType type ) throws PasswordResetException, AccessDeniedException, InstantiationException,
        IllegalAccessException, ClassNotFoundException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    IAttribute attribute = _attributes.get( type );
    assertNotNull( attribute );
    request.setParameter( "id_attribute", Integer.toString( attribute.getIdAttribute( ) ) );
    String strTitle = getRandomName( );
    request.setParameter( "title", strTitle );
    request.setParameter( "width", "5" );

    request.setParameter( SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance( ).getToken( request, attribute.getTemplateModifyAttribute( ) ) );

    Utils.registerAdminUserWithRigth( request, new AdminUser( ), "CORE_USERS_MANAGEMENT" );
    AttributeJspBean instance = new AttributeJspBean( );
    instance.init( request, "CORE_USERS_MANAGEMENT" );

    instance.doModifyAttribute( request );
    IAttribute stored = AttributeService.getInstance( ).getAttributeWithoutFields( attribute.getIdAttribute( ), Locale.FRANCE );
    assertNotNull( stored );
    assertEquals( strTitle, stored.getTitle( ) );
}
 
Example #2
Source File: JWTFilterTest.java    From alchemy with Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTFilterWrongScheme() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
 
Example #3
Source File: _SwaggerBasePathRewritingFilterTest.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void run_on_valid_response() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

    MockHttpServletResponse response = new MockHttpServletResponse();
    context.setResponse(response);

    InputStream in = IOUtils.toInputStream("{\"basePath\":\"/\"}");
    context.setResponseDataStream(in);

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());
    assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody());
}
 
Example #4
Source File: FeatureDatasetTypeTest.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void getFDForDatasetScanStationDataset() throws IOException {
  MockHttpServletRequest req = new MockHttpServletRequest();
  MockHttpServletResponse res = new MockHttpServletResponse();

  String reqPath = "testStationScan/Surface_METAR_20130826_0000.nc";
  FeatureDataset fd = TdsRequestedDataset.getPointDataset(req, res, reqPath);
  if (fd == null) {
    DataRootManager.DataRootMatch match = matcher.findDataRootMatch(reqPath);
    if (match == null) {
      Formatter f = new Formatter();
      matcher.showRoots(f);
      System.out.printf("DataRoots%n%s%n", f);
    }

  }
  assertNotNull(fd);
  assertEquals(FeatureType.STATION, fd.getFeatureType());
}
 
Example #5
Source File: PageListControllerTest.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * The servlet is supposed to embed the audit id the page is 
 * about. If not, the ForbiddenPageException is caught.
 * @throws Exception 
 */
public void testDisplayPageListWithoutAuditId() throws Exception {
    System.out.println("testDisplayPageListWithoutAuditId");
    
    // The servlet is supposed to embed the webresource id the page is 
    // about. If not, the access denied page is returned
     try {
        instance.displayPageList(
                new MockHttpServletRequest(), 
                new MockHttpServletResponse(), 
                new ExtendedModelMap());
        assertTrue(false);
    } catch (AuditParameterMissingException fbe) {
        assertTrue(true);
    }
}
 
Example #6
Source File: SwaggerBasePathRewritingFilterTest.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
@Test
public void run_on_valid_response_gzip() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

    MockHttpServletResponse response = new MockHttpServletResponse();
    context.setResponseGZipped(true);
    context.setResponse(response);

    context.setResponseDataStream(new ByteArrayInputStream(gzipData("{\"basePath\":\"/\"}")));

    filter.run();

    assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8");

    InputStream responseDataStream = new GZIPInputStream(context.getResponseDataStream());
    String responseBody = IOUtils.toString(responseDataStream, StandardCharsets.UTF_8);
    assertThat(responseBody).isEqualTo("{\"basePath\":\"/service1\"}");
}
 
Example #7
Source File: MockHttpServletRequestBuilderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void mergeInvokesDefaultRequestPostProcessorFirst() {
	final String ATTR = "ATTR";
	final String EXEPCTED = "override";

	MockHttpServletRequestBuilder defaultBuilder =
			new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo/bar")
			.with(requestAttr(ATTR).value("default"));

	builder
			.with(requestAttr(ATTR).value(EXEPCTED));

	builder.merge(defaultBuilder);

	MockHttpServletRequest request = builder.buildRequest(servletContext);
	request = builder.postProcessRequest(request);

	assertEquals(EXEPCTED, request.getAttribute(ATTR));
}
 
Example #8
Source File: JsonRpcServerTest.java    From jsonrpc4j with MIT License 6 votes vote down vote up
@Test
public void testGetMethod_base64Params() throws Exception {
	EasyMock.expect(mockService.testMethod("Whir?inaki")).andReturn("For?est");
	EasyMock.replay(mockService);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test-get");
	MockHttpServletResponse response = new MockHttpServletResponse();

	request.addParameter("id", Integer.toString(123));
	request.addParameter("method", "testMethod");
	request.addParameter("params", net.iharder.Base64.encodeBytes("[\"Whir?inaki\"]".getBytes(StandardCharsets.UTF_8)));

	jsonRpcServer.handle(request, response);

	assertTrue("application/json-rpc".equals(response.getContentType()));
	checkSuccessfulResponse(response);
}
 
Example #9
Source File: JWTFilterTest.java    From ehcache3-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTFilter() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
    assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
}
 
Example #10
Source File: AutomaticDispatcherUrlServiceTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testLocalizeConfigured() {
	AutomaticDispatcherUrlService adus = new AutomaticDispatcherUrlService();
	adus.setLocalDispatcherUrl("http://my:8080/local/dispatcher/");

	// set mock request in context holder
	MockHttpServletRequest mockRequest = new MockHttpServletRequest();
	mockRequest.setScheme("http");
	mockRequest.setServerName("myhost");
	mockRequest.setServerPort(80);
	mockRequest.setLocalName("localhost");
	mockRequest.setLocalPort(8080);
	mockRequest.setContextPath("/test");
	mockRequest.addHeader(X_FORWARD_HOST_HEADER, "geomajas.org");
	ServletRequestAttributes attributes = new ServletRequestAttributes(mockRequest);
	RequestContextHolder.setRequestAttributes(attributes);
	Assert.assertEquals("http://my:8080/local/dispatcher/something", adus.localize("http://geomajas.org/test/d/something"));

	// clean up
	RequestContextHolder.setRequestAttributes(null);
}
 
Example #11
Source File: RoleManagementJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testDoCreateRoleInvalidToken( ) throws AccessDeniedException
{
    RoleManagementJspBean bean = new RoleManagementJspBean( );
    MockHttpServletRequest request = new MockHttpServletRequest( );
    final String roleName = getRandomName( );
    request.setParameter( "role_key", roleName );
    request.setParameter( "role_description", roleName );
    request.setParameter( SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance( ).getToken( request, "admin/rbac/create_role.html" ) + "b" );
    try
    {
        assertFalse(RBACRoleHome.checkExistRole( roleName ) );
        bean.doCreateRole( request );
        fail( "Should have thrown" );
    }
    catch ( AccessDeniedException e )
    {
        assertFalse(RBACRoleHome.checkExistRole( roleName ) );
    }
    finally
    {
        RBACRoleHome.remove( roleName );
    }
}
 
Example #12
Source File: JdbcServlet.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void executeApp() throws Exception {
    if (connection == null) {
        connection = JDBCDriver.getConnection("jdbc:hsqldb:mem:test", null);
        Statement statement = connection.createStatement();
        try {
            statement.execute("create table employee (name varchar(100))");
            statement.execute("insert into employee (name) values ('john doe')");
            statement.execute("insert into employee (name) values ('jane doe')");
            statement.execute("insert into employee (name) values ('sally doe')");
        } finally {
            statement.close();
        }
    }
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/jdbcservlet");
    MockHttpServletResponse response = new MockHttpServletResponse();
    service((ServletRequest) request, (ServletResponse) response);
}
 
Example #13
Source File: CrnkServletRejectJsonTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testAcceptJsonApi() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    request.setMethod("GET");
    request.setContextPath("");
    request.setServletPath("/api");
    request.setPathInfo("/tasks/1");
    request.setRequestURI("/api/tasks/1");
    request.addHeader("Accept", HttpHeaders.JSONAPI_CONTENT_TYPE);

    MockHttpServletResponse response = new MockHttpServletResponse();

    servlet.service(request, response);

    String responseContent = response.getContentAsString();

    log.debug("responseContent: {}", responseContent);
    assertNotNull(responseContent);

    assertJsonPartEquals("tasks", responseContent, "data.type");
    assertJsonPartEquals("\"1\"", responseContent, "data.id");
    assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data.relationships.project.links");
}
 
Example #14
Source File: InternalServerErrorControllerTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenericError() {
    MessageService messageService = new YamlMessageService();
    InternalServerErrorController errorController = new InternalServerErrorController(messageService);

    MockHttpServletRequest request = new MockHttpServletRequest();

    request.setAttribute(ErrorUtils.ATTR_ERROR_EXCEPTION, new Exception("Hello"));
    request.setAttribute(ErrorUtils.ATTR_ERROR_STATUS_CODE, 523);
    request.setAttribute(RequestDispatcher.FORWARD_REQUEST_URI, "/uri");

    ResponseEntity<ApiMessageView> response = errorController.error(request);

    assertEquals(523,  response.getStatusCodeValue());
    assertEquals("org.zowe.apiml.common.internalRequestError",  response.getBody().getMessages().get(0).getMessageKey());
    assertTrue(response.getBody().getMessages().get(0).getMessageContent().contains("Hello"));
    assertTrue(response.getBody().getMessages().get(0).getMessageContent().contains("/uri"));
}
 
Example #15
Source File: TrustedUserAuthenticationFilterTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testTrustedUserFilterNoSpel() throws Exception
{
    // Override configuration.
    Map<String, Object> overrideMap = new HashMap<>();
    overrideMap.put(ConfigurationValue.SECURITY_ENABLED_SPEL_EXPRESSION.getKey(), "");
    modifyPropertySourceInEnvironment(overrideMap);

    try
    {
        // Invalidate user session if exists.
        invalidateApplicationUser(null);

        trustedUserAuthenticationFilter.init(new MockFilterConfig());
        trustedUserAuthenticationFilter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain());

        assertNoUserInContext();
    }
    finally
    {
        // Restore the property sources so we don't affect other tests.
        restorePropertySourceInEnvironment();
    }
}
 
Example #16
Source File: AdminWorkgroupJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testDoRemoveWorkgroupNoToken( ) throws AccessDeniedException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.setParameter( "workgroup_key", adminWorkgroup.getKey( ) );

    assertTrue( AdminWorkgroupHome.checkExistWorkgroup( adminWorkgroup.getKey( ) ) );
    try
    {
        bean.doRemoveWorkgroup( request );
        fail( "Should have thrown" );
    }
    catch( AccessDeniedException e )
    {
        assertTrue( AdminWorkgroupHome.checkExistWorkgroup( adminWorkgroup.getKey( ) ) );
    }
}
 
Example #17
Source File: PluginJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testDoUninstallPluginInvalidToken( ) throws AccessDeniedException
{
    PluginService.getPlugin( PLUGIN_NAME ).install( );
    assertTrue( PluginService.isPluginEnable( PLUGIN_NAME ) );
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.addParameter( "plugin_name", PLUGIN_NAME );
    request.addParameter( SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance( ).getToken( request, "jsp/admin/system/DoUninstallPlugin.jsp" ) + "b" );
    try
    {
        instance.doUninstallPlugin( request, request.getServletContext( ) );
        fail( "Should have thrown" );
    }
    catch( AccessDeniedException e )
    {
        assertTrue( PluginService.isPluginEnable( PLUGIN_NAME ) );
    }
}
 
Example #18
Source File: JWTFilterUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testJWTFilterWrongScheme() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
 
Example #19
Source File: MailingListJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testDoRemoveMailingListInvalidToken( ) throws AccessDeniedException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.setParameter( "id_mailinglist", Integer.toString( mailingList.getId( ) ) );
    request.setParameter( SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance( ).getToken( request, "jsp/admin/mailinglist/DoRemoveMailingList.jsp" ) + "b" );

    assertNotNull( MailingListHome.findByPrimaryKey( mailingList.getId( ) ) );
    try
    {
        bean.doRemoveMailingList( request );
        fail( "Should have thrown" );
    }
    catch( AccessDeniedException e )
    {
        assertNotNull( MailingListHome.findByPrimaryKey( mailingList.getId( ) ) );
    }
}
 
Example #20
Source File: InspektrThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapterTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
protected MockHttpServletResponse loginUnsuccessfully(final String username, final String fromAddress)
        throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    request.setMethod("POST");
    request.setParameter("username", username);
    request.setRemoteAddr(fromAddress);
    final MockRequestContext context = new MockRequestContext();
    context.setCurrentEvent(new Event("", "error"));
    request.setAttribute("flowRequestContext", context);
    ClientInfoHolder.setClientInfo(new ClientInfo(request));

    getThrottle().preHandle(request, response, null);

    try {
        authenticationManager.authenticate(badCredentials(username));
    } catch (final AuthenticationException e) {
        getThrottle().postHandle(request, response, null, null);
        return response;
    }
    fail("Expected AuthenticationException");
    return null;
}
 
Example #21
Source File: FailedAuthenticationHandlerTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testOnAuthenticationFailure() throws ServletException {
    AuthExceptionHandler authExceptionHandler = mock(AuthExceptionHandler.class);

    MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
    MockHttpServletResponse httpServletResponse = new MockHttpServletResponse();

    FailedAuthenticationHandler failedAuthenticationHandler = new FailedAuthenticationHandler(authExceptionHandler);

    BadCredentialsException badCredentialsException = new BadCredentialsException("ERROR");
    failedAuthenticationHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, badCredentialsException);

    verify(authExceptionHandler).handleException(
        httpServletRequest,
        httpServletResponse,
        badCredentialsException
    );
}
 
Example #22
Source File: OptionsEndpointFilterTest.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
@Test
public void doFilter_with_error_test() throws IOException, ServletException {
    OptionsProvider optionsProvider = mock(OptionsProvider.class);
    doThrow(new RuntimeException()).when(optionsProvider).getAttestationOptions(any(), any(), any());
    OptionsEndpointFilter optionsEndpointFilter = new OptionsEndpointFilter(optionsProvider, objectConverter);
    AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
    optionsEndpointFilter.setTrustResolver(trustResolver);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI(OptionsEndpointFilter.FILTER_URL);
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();

    optionsEndpointFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
 
Example #23
Source File: SampleKatharsisServletTest.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testKatharsisMatchingException() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setContextPath("");
	request.setServletPath("/api");
	request.setPathInfo("/tasks-matching-exception");
	request.setRequestURI("/api/matching-exception");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	request.addHeader("Accept", "*/*");
	MockHttpServletResponse response = new MockHttpServletResponse();
	katharsisServlet.service(request, response);

	String responseContent = response.getContentAsString();
	assertTrue("Response should not be returned for non matching resource type", StringUtils.isBlank(responseContent));
	assertEquals(404, response.getStatus());

}
 
Example #24
Source File: AdminMenuJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testDoModifyAccessibilityMode( ) throws AccessDeniedException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.setParameter( SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance( ).getToken( request, AccessibilityModeAdminUserMenuItemProvider.TEMPLATE ) );

    getUser( request );
    Utils.registerAdminUser( request, _user );
    boolean bAccessibilityMode = _user.getAccessibilityMode( );
    try
    {
        AdminMenuJspBean instance = new AdminMenuJspBean( );
        instance.doModifyAccessibilityMode( request );
        assertEquals( !bAccessibilityMode, _user.getAccessibilityMode( ) );
    }
    finally
    {
        _user.setAccessibilityMode( bAccessibilityMode );
        AdminUserHome.update( _user );
    }
}
 
Example #25
Source File: MockHttpServletRequestBuilderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void flashAttribute() {
	this.builder.flashAttr("foo", "bar");
	MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);

	FlashMap flashMap = new SessionFlashMapManager().retrieveAndUpdate(request, null);
	assertNotNull(flashMap);
	assertEquals("bar", flashMap.get("foo"));
}
 
Example #26
Source File: TestUtils.java    From springboot-shiro-cas-mybatis with MIT License 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 #27
Source File: ContentItemTest.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testContentItemThrowsBadContentItems() throws Exception {

	MockHttpServletRequest req = new MockHttpServletRequest();
	req.addParameter("data", "{\"eggs\": \"chips\"}");
	req.addParameter(ContentItem.CONTENT_ITEMS, "[\"bad\"]");
	expectedEx.expect(RuntimeException.class);
	expectedEx.expectMessage(ContentItem.BAD_CONTENT_MESSAGE);
	ContentItem contentItem = new ContentItem(req);
}
 
Example #28
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 #29
Source File: AdminUserJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testDoModifyAdminUserSuccess( ) throws AccessDeniedException, UserNotSignedException
{
    AdminUser userToModify = getUserToModify( );
    try
    {
        AdminUserJspBean bean = new AdminUserJspBean( );
        MockHttpServletRequest request = new MockHttpServletRequest( );
        AdminAuthenticationService.getInstance( ).registerUser( request, AdminUserHome.findUserByLogin( "admin" ) );
        request.addParameter( "id_user", Integer.toString( userToModify.getUserId( ) ) );
        final String modifiedName = userToModify.getAccessCode( ) + "_mod";
        request.addParameter( "access_code", modifiedName );
        request.addParameter( "last_name", modifiedName );
        request.addParameter( "first_name", modifiedName );
        request.addParameter( "email", userToModify.getEmail( ) );
        request.addParameter( "status", Integer.toString( AdminUser.NOT_ACTIVE_CODE ) );
        request.addParameter( "language", Locale.KOREA.toString( ) );
        request.setParameter( SecurityTokenService.PARAMETER_TOKEN, SecurityTokenService.getInstance( ).getToken( request, "jsp/admin/user/ModifyUser.jsp" ) );
        bean.doModifyAdminUser( request );
        AdminMessage message = AdminMessageService.getMessage( request );
        assertNull( message );
        AdminUser stored = AdminUserHome.findByPrimaryKey( userToModify.getUserId( ) );
        assertNotNull( stored );
        assertEquals( modifiedName, stored.getAccessCode( ) );
        assertEquals( modifiedName, stored.getFirstName( ) );
        assertEquals( modifiedName, stored.getLastName( ) );
        assertEquals( AdminUser.NOT_ACTIVE_CODE, stored.getStatus( ) );
        assertEquals( Locale.KOREA.toString( ).toLowerCase( ), stored.getLocale( ).toString( ).toLowerCase( ) );
    }
    finally
    {
        disposeOfUser( userToModify );
    }
}
 
Example #30
Source File: BaseTest.java    From xmanager with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
			.alwaysDo(MockMvcResultHandlers.print())
			.build();
	request = new MockHttpServletRequest();
	request.setCharacterEncoding("UTF-8");
	response = new MockHttpServletResponse();
}