org.springframework.mock.web.MockHttpServletResponse Java Examples

The following examples show how to use org.springframework.mock.web.MockHttpServletResponse. 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: JsonRpcServerTest.java    From jsonrpc4j with MIT License 7 votes vote down vote up
@Test
public void test_contentType() throws Exception {
	EasyMock.expect(mockService.testMethod("Whir?inaki")).andReturn("For?est");
	EasyMock.replay(mockService);

	MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test-post");
	MockHttpServletResponse response = new MockHttpServletResponse();

	request.setContentType("application/json");
	request.setContent("{\"jsonrpc\":\"2.0\",\"id\":123,\"method\":\"testMethod\",\"params\":[\"Whir?inaki\"]}".getBytes(StandardCharsets.UTF_8));

	jsonRpcServer.setContentType("flip/flop");

	jsonRpcServer.handle(request, response);

	assertTrue("flip/flop".equals(response.getContentType()));
	checkSuccessfulResponse(response);
}
 
Example #2
Source File: AuthenticationViaFormActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyRenewWithServiceAndBadCredentials() throws Exception {
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(c);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
    request.addParameter("renew", "true");
    request.addParameter("service", "test");

    final Credential c2 = TestUtils.getCredentialsWithDifferentUsernameAndPassword();
    context.setExternalContext(new ServletExternalContext(
        new MockServletContext(), request, new MockHttpServletResponse()));
    putCredentialInRequestScope(context, c2);
    context.getRequestScope().put(
        "org.springframework.validation.BindException.credentials",
        new BindException(c2, "credentials"));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("error", this.action.submit(context, c2, messageContext).getId());
}
 
Example #3
Source File: SwaggerBasePathRewritingFilterTest.java    From jhipster-microservices-example with Apache License 2.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.setResponseGZipped(false);
    context.setResponse(response);

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

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());
    assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody());
}
 
Example #4
Source File: AuthenticationViaFormActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
    public void testSuccessfulAuthenticationWithServiceAndWarn()
        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");
        request.addParameter("service", "test");

        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 #5
Source File: PageListControllerTest.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * The PageList is displayed when the webResource is a Site instance. 
 * When the request has no TgolKeyStore.STATUS_KEY parameter set, 
 * the page that lists the number of page by Http Status Code has to be 
 * returned
 * 
 * @throws Exception 
 */
public void testDisplayPageList() throws Exception {
    System.out.println("testDisplayPageList");
    
    setUpMockAuditDataService(SITE_AUDIT_GENERAL_PAGE_LIST_ID);
    setUpMockUserDataService();
    setUpActDataService(true);
    setUpMockAuthenticationContext();
    setUpAuditStatisticsFactory();
    
    List<String> authorizedScopeForPageList = new ArrayList();
    authorizedScopeForPageList.add("DOMAIN");
    instance.setAuthorizedScopeForPageList(authorizedScopeForPageList);
    
    HttpServletResponse response = new MockHttpServletResponse();
    MockHttpServletRequest request = new MockHttpServletRequest();
    String expResult = TgolKeyStore.PAGE_LIST_VIEW_NAME;
    request.addParameter(TgolKeyStore.AUDIT_ID_KEY, String.valueOf(SITE_AUDIT_GENERAL_PAGE_LIST_ID));
    String result = instance.displayPageList(request, response, new ExtendedModelMap());
    assertEquals(expResult, result);
}
 
Example #6
Source File: Swagger2MarkupTest.java    From springrestdoc with MIT License 6 votes vote down vote up
@Test
public void createJsonFileFromSwaggerEndpoint() throws Exception {
    String outputDir = Optional.ofNullable(System.getProperty("io.springfox.staticdocs.outputDir"))
            .orElse("build/swagger");
    System.err.println(outputDir);
    MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn();

    MockHttpServletResponse response = mvcResult.getResponse();
    String swaggerJson = response.getContentAsString();
    Files.createDirectories(Paths.get(outputDir));
    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"),
            StandardCharsets.UTF_8)) {
        writer.write(swaggerJson);
    }
}
 
Example #7
Source File: HttpHeaderAuthenticationFilterTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpHeaderAuthenticationFilterMultipleRoles() throws Exception
{
    modifyPropertySourceInEnvironment(getDefaultSecurityEnvironmentVariables());

    try
    {
        MockHttpServletRequest request =
            getRequestWithHeaders(USER_ID, "testFirstName", "testLastName", "testEmail", "testRole1,testRole2", "Wed, 11 Mar 2015 10:24:09");
        // Invalidate user session if exists.
        invalidateApplicationUser(request);

        httpHeaderAuthenticationFilter.init(new MockFilterConfig());
        httpHeaderAuthenticationFilter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());

        Set<String> expectedRoles = new HashSet<>();
        expectedRoles.add("testRole1");
        expectedRoles.add("testRole2");
        validateHttpHeaderApplicationUser(USER_ID, "testFirstName", "testLastName", "testEmail", expectedRoles, "Wed, 11 Mar 2015 10:24:09", null, null);
    }
    finally
    {
        restorePropertySourceInEnvironment();
    }
}
 
Example #8
Source File: SwaggerJsonTest.java    From alcor with Apache License 2.0 6 votes vote down vote up
@Test
public void createSpringfoxSwaggerJson() throws Exception{
    String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
    MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn();

    MockHttpServletResponse response = mvcResult.getResponse();
    String swaggerJson = response.getContentAsString();
    Files.createDirectories(Paths.get(outputDir));
    try(BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)){
        writer.write(swaggerJson);
    }

    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
            .withGeneratedExamples()
            .withInterDocumentCrossReferences()
            .build();
    Swagger2MarkupConverter.from(Paths.get(outputDir,"swagger.json"))
            .withConfig(config)
            .build()
            .toFile(Paths.get(outputDir, "swagger"));
}
 
Example #9
Source File: TabbedGroupControllerTest.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Test
public final void testProcessCancel() {
	try {
		MockHttpServletRequest request = new MockHttpServletRequest();
		MockHttpServletResponse response = new MockHttpServletResponse();
		DefaultCommand comm = new DefaultCommand();
		comm.setMode(DefaultCommand.MODE_EDIT);

		Tab currTab = testInstance.getTabConfig().getTabs().get(0);
		assertTrue(currTab != null);
		BindException aError = new BindException(new DefaultSiteCommand(),
				null);
		ModelAndView mav = testInstance.processCancel(currTab, request,
				response, comm, aError);
		assertTrue(mav != null);
		assertTrue(mav.getViewName().equals(
				"redirect:/curator/groups/search.html"));
	} catch (Exception e) {
		String message = e.getClass().toString() + " - " + e.getMessage();
		log.debug(message);
		fail(message);
	}
}
 
Example #10
Source File: SwaggerBasePathRewritingFilterTest.java    From okta-jhipster-microservices-oauth-example with Apache License 2.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.setResponseGZipped(false);
    context.setResponse(response);

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

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());
    assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody());
}
 
Example #11
Source File: RequestUtil.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
public static MockHttpServletResponse sendPut(MockMvc mockMvc,String uriWithParam,String requestJson){
    MockHttpServletResponse mockResponse = null;
    try {
        mockResponse = mockMvc
                .perform(
                        put(uriWithParam, ConstantsForTest.JSON)
                        .characterEncoding(ConstantsForTest.UTF8)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(requestJson)
                        )
                .andReturn()
                .getResponse();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return mockResponse;
}
 
Example #12
Source File: HttpHeaderAuthenticationFilterTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpHeaderAuthenticationFilterNoRoles() throws Exception
{
    modifyPropertySourceInEnvironment(getDefaultSecurityEnvironmentVariables());

    try
    {
        MockHttpServletRequest request = getRequestWithHeaders(USER_ID, "testFirstName", "testLastName", "testEmail", null, "Wed, 11 Mar 2015 10:24:09");

        // Invalidate user session if exists.
        invalidateApplicationUser(request);

        httpHeaderAuthenticationFilter.init(new MockFilterConfig());
        httpHeaderAuthenticationFilter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());

        validateHttpHeaderApplicationUser(USER_ID, "testFirstName", "testLastName", "testEmail", (String) null, "Wed, 11 Mar 2015 10:24:09", null, null);
    }
    finally
    {
        restorePropertySourceInEnvironment();
    }
}
 
Example #13
Source File: OpenApiTestBase.java    From iaf with Apache License 2.0 6 votes vote down vote up
protected String service(HttpServletRequest request) throws ServletException, IOException {
	try {
		MockHttpServletResponse response = new MockHttpServletResponse();
		ApiListenerServlet servlet = servlets.get();
		assertNotNull("Servlet cannot be found!??", servlet);

		servlet.service(request, response);

		return response.getContentAsString();
	} catch (Throwable t) {
		//Silly hack to try and make the error visible in Travis.
		assertTrue(ExceptionUtils.getStackTrace(t), false);
	}

	//This should never happen because of the assertTrue(false) statement in the catch cause.
	return null;
}
 
Example #14
Source File: ServletResponseResultWriterTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testPrettyPrint() throws Exception {
  MockHttpServletResponse response = new MockHttpServletResponse();
  ServletResponseResultWriter writer = new ServletResponseResultWriter(response, null,
      true /* prettyPrint */, true /* addContentLength */);
  writer.write(ImmutableMap.of("one", "two", "three", "four"));
  // If the response is pretty printed, there should be at least two newlines.
  String body = response.getContentAsString();
  int index = body.indexOf('\n');
  assertThat(index).isAtLeast(0);
  index = body.indexOf('\n', index + 1);
  assertThat(index).isAtLeast(0);
  // Unlike the Jackson pretty printer, which will either put no space around a colon or a space
  // on both sides, we want to ensure that a space comes after a colon, but not before.
  assertThat(body).contains("\": ");
  assertThat(body).doesNotContain("\" :");
}
 
Example #15
Source File: ManageRegisteredServicesMultiActionControllerTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyDeleteService() throws Exception {
    final RegisteredServiceImpl r = new RegisteredServiceImpl();
    r.setId(1200);
    r.setName("name");
    r.setServiceId("serviceId");
    r.setEvaluationOrder(1);

    this.servicesManager.save(r);

    final MockHttpServletResponse response = new MockHttpServletResponse();
    this.controller.manage(response);
    this.controller.deleteRegisteredService(1200, response);

    assertNull(this.servicesManager.findServiceBy(1200));
    assertTrue(response.getContentAsString().contains("serviceName"));
}
 
Example #16
Source File: FlashLoadingFilterTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInitializeFlashIfNotPresent() throws IOException, ServletException {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();

    FilterChain filterChain = new MockFilterChain() {
        @Override
        public void doFilter(ServletRequest request, ServletResponse response) {
            messageKey = service.add(new FlashMessageModel("my message", "error"));
            flash = service.get(messageKey);
        }
    };
    assertThat(messageKey, is(nullValue()));
    filter.doFilter(req, res, filterChain);
    assertThat(messageKey, not(nullValue()));
    assertThat(flash.toString(), is("my message"));
    assertThat(flash.getFlashClass(), is("error"));
}
 
Example #17
Source File: RssFeedServletTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequestNewVersionsOfArtifact()
    throws Exception
{
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI( "/feeds/org/apache/archiva/artifact-two" );
    request.addHeader( "User-Agent", "Apache Archiva unit test" );
    request.setMethod( "GET" );

    //WebRequest request = new GetMethodWebRequest( "http://localhost/feeds/org/apache/archiva/artifact-two" );

    Base64 encoder = new Base64( 0, new byte[0] );
    String userPass = "user1:password1";
    String encodedUserPass = encoder.encodeToString( userPass.getBytes() );
    request.addHeader( "Authorization", "BASIC " + encodedUserPass );

    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    rssFeedServlet.doGet( request, mockHttpServletResponse );

    assertEquals( RssFeedServlet.MIME_TYPE, mockHttpServletResponse.getHeader( "CONTENT-TYPE" ) );
    assertNotNull( "Should have recieved a response", mockHttpServletResponse.getContentAsString() );
    assertEquals( "Should have been an OK response code.", HttpServletResponse.SC_OK,
                  mockHttpServletResponse.getStatus() );
}
 
Example #18
Source File: TabbedContollerTest.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Test
public void testShowForm() {
	//boolean result;
	try {
		assertTrue(tc!=null);		
		MockHttpServletRequest req = new MockHttpServletRequest();
		MockHttpServletResponse res = new MockHttpServletResponse();
		req.addParameter("_tab_edit", "_tab_edit");
		req.addParameter("_tab_current_page","1");
		TabbedModelAndView tmav = (TabbedModelAndView)tc.processFormSubmission(req, res, null, null);
		assertTrue(methodsCalled.get(0) == "TabbedController.switchToEditMode");
		assertTrue(methodsCalled.get(1) == "TabHandler.preProcessNextTab");
		assertTrue(tmav.getTabStatus().getCurrentTab().getPageId() == "1");

	}
	catch (Exception e)
	{
		String message = e.getClass().toString() + " - " + e.getMessage();
		log.debug(message);
		fail(message);
	}
}
 
Example #19
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 #20
Source File: ServiceValidateControllerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidServiceTicketWithInsecurePgtUrl() throws Exception {
    this.serviceValidateController.setProxyHandler(new Cas10ProxyHandler());
    final String tId = getCentralAuthenticationService()
            .createTicketGrantingTicket(TestUtils.getCredentialsWithSameUsernameAndPassword());
    final String sId = getCentralAuthenticationService().grantServiceTicket(tId, TestUtils.getService());

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("service", TestUtils.getService().getId());
    request.addParameter("ticket", sId);
    request.addParameter("pgtUrl", "http://www.github.com");

    final ModelAndView modelAndView = this.serviceValidateController
            .handleRequestInternal(request, new MockHttpServletResponse());
    assertEquals(ServiceValidateController.DEFAULT_SERVICE_FAILURE_VIEW_NAME, modelAndView.getViewName());
    
}
 
Example #21
Source File: AuthenticationViaFormActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@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 #22
Source File: JsonRpcServerTest.java    From jsonrpc4j with MIT License 6 votes vote down vote up
@Test
public void testGetMethod_unencodedParams() 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", "[\"Whir?inaki\"]");

	jsonRpcServer.handle(request, response);

	assertTrue("application/json-rpc".equals(response.getContentType()));
	checkSuccessfulResponse(response);
}
 
Example #23
Source File: SiteControllerTest.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Test
public final void testShowForm() {
	try
	{
		MockHttpServletRequest request = new MockHttpServletRequest();
		MockHttpServletResponse response = new MockHttpServletResponse();
		DefaultSiteCommand comm = new DefaultSiteCommand();
		comm.setEditMode(true);
		comm.setSiteOid(null);
		
		BindException aError = new BindException(new DefaultSiteCommand(), null);
		ModelAndView mav = testInstance.showForm(request, response, comm, aError);
		assertTrue(mav != null);
		assertTrue(mav.getViewName().equals("site"));
		SiteEditorContext context = testInstance.getEditorContext(request);
		assertSame(context.getSite().getOwningAgency(), AuthUtil.getRemoteUserObject().getAgency());
	}
	catch (Exception e)
	{
		String message = e.getClass().toString() + " - " + e.getMessage();
		log.debug(message);
		fail(message);
	}
}
 
Example #24
Source File: JWTFilterTest.java    From e-commerce-microservice 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 #25
Source File: SwaggerJsonTest.java    From alcor with Apache License 2.0 6 votes vote down vote up
@Test
public void createSpringfoxSwaggerJson() throws Exception{
    String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
    MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andReturn();
    
    MockHttpServletResponse response = mvcResult.getResponse();
    String swaggerJson = response.getContentAsString();
    Files.createDirectories(Paths.get(outputDir));
    try(BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)){
        writer.write(swaggerJson);
    }

    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
        .withGeneratedExamples()
        .withInterDocumentCrossReferences()
        .build();
    Swagger2MarkupConverter.from(Paths.get(outputDir,"swagger.json"))
        .withConfig(config)
        .build()
        .toFile(Paths.get(outputDir, "swagger"));
}
 
Example #26
Source File: MembersHandlerTest.java    From webcurator with Apache License 2.0 5 votes vote down vote up
@Test
public final void testPreProcessNextTab() {
	HttpServletRequest aReq = new MockHttpServletRequest();
	TargetManager targetManager = new MockTargetManager(testFile);
	testInstance.setTargetManager(targetManager);
	testSetSubGroupSeparator();
	TargetGroup targetGroup = targetManager.loadGroup(15000L);
	GroupsEditorContext groupsEditorContext = new GroupsEditorContext(targetGroup,true);
	aReq.getSession().setAttribute(TabbedGroupController.EDITOR_CONTEXT, groupsEditorContext);

	HttpServletResponse aResp = new MockHttpServletResponse(); 
	MembersCommand aCmd = new MembersCommand();
	TabbedController tc = new TabbedGroupController();

	TabConfig tabConfig = new TabConfig();
	tabConfig.setViewName("group");
	List<Tab> tabs = getTabList(targetManager);
	tabConfig.setTabs(tabs);

	tc.setTabConfig(tabConfig);
	tc.setDefaultCommandClass(org.webcurator.ui.groups.command.DefaultCommand.class);
	
	Tab currentTab = tabs.get(1);
	BindException aErrors = new BindException(aCmd, "MembersCommand");
	ModelAndView mav = testInstance.preProcessNextTab(tc, currentTab, aReq, aResp, aCmd, aErrors);
	assertTrue(mav.getModel().get("command") instanceof MembersCommand);
}
 
Example #27
Source File: HerdErrorInformationExceptionHandlerTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testDataTruncationException() throws Exception
{
    validateErrorInformation(
        exceptionHandler.handlePersistenceException(getPersistenceException(new DataTruncation(1, true, true, 5, 10)), new MockHttpServletResponse()),
        HttpStatus.BAD_REQUEST, false);
}
 
Example #28
Source File: InitialFlowSetupActionTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifySettingContextPath() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setContextPath(CONST_CONTEXT_PATH);
    final MockRequestContext context = new MockRequestContext();
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));

    this.action.doExecute(context);

    assertEquals(CONST_CONTEXT_PATH + "/", this.warnCookieGenerator.getCookiePath());
    assertEquals(CONST_CONTEXT_PATH + "/", this.tgtCookieGenerator.getCookiePath());
}
 
Example #29
Source File: PrintingResultHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Print the response.
 */
protected void printResponse(MockHttpServletResponse response) throws Exception {
	String body = (response.getCharacterEncoding() != null ?
			response.getContentAsString() : MISSING_CHARACTER_ENCODING);

	this.printer.printValue("Status", response.getStatus());
	this.printer.printValue("Error message", response.getErrorMessage());
	this.printer.printValue("Headers", getResponseHeaders(response));
	this.printer.printValue("Content type", response.getContentType());
	this.printer.printValue("Body", body);
	this.printer.printValue("Forwarded URL", response.getForwardedUrl());
	this.printer.printValue("Redirected URL", response.getRedirectedUrl());
	printCookies(response.getCookies());
}
 
Example #30
Source File: OAuth2AuthenticationServiceTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testInvalidPassword() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setServerName("www.test.com");
    Map<String, String> params = new HashMap<>();
    params.put("username", "user");
    params.put("password", "user2");
    params.put("rememberMe", "false");
    MockHttpServletResponse response = new MockHttpServletResponse();
    expectedException.expect(InvalidPasswordException.class);
    authenticationService.authenticate(request, response, params);
}