Tabnine Logo
MockHttpServletRequestBuilder
Code IndexAdd Tabnine to your IDE (free)

How to use
MockHttpServletRequestBuilder
in
org.springframework.test.web.servlet.request

Best Java code snippets using org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder (Showing top 20 results out of 918)

Refine searchRefine arrow

  • ResultActions
  • MockMvc
  • MockMvcRequestBuilders
  • MockMvcResultMatchers
  • StatusResultMatchers
origin: cloudfoundry/uaa

private void tryLoginWithWrongSecretInBody(String clientId) throws Exception {
  mockMvc.perform(post("/oauth/token")
      .accept(MediaType.APPLICATION_JSON_VALUE)
      .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
      .param("grant_type", "client_credentials")
      .param("client_id", clientId)
      .param("client_secret", BADSECRET)
  )
      .andExpect(status().isUnauthorized())
      .andReturn().getResponse().getContentAsString();
}
origin: requery/requery

  private void postUserAndExpectSame(String userJson) throws Exception {
    mockMvc.perform(
        post("/user")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content(userJson)
    ).andExpect(status().isCreated()).andExpect(content().json(userJson));
  }
}
origin: spring-projects/spring-framework

@Test
public void stringWithMatcherAndMissingResponseHeader() throws Exception {
  this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, now))
      .andExpect(status().isNotModified())
      .andExpect(header().string("X-Custom-Header", nullValue()));
}
origin: spring-projects/spring-security

@Test
public void requestTokenWhenUsingPasswordGrantTypeThenOk()
    throws Exception {
  this.mvc.perform(post("/oauth/token")
    .param("grant_type", "password")
    .param("username", "subject")
    .param("password", "password")
    .header("Authorization", "Basic cmVhZGVyOnNlY3JldA=="))
      .andExpect(status().isOk());
}
origin: spring-projects/spring-framework

private ClientHttpResponse getClientHttpResponse(
    HttpMethod httpMethod, URI uri, HttpHeaders requestHeaders, byte[] requestBody) {
  try {
    MockHttpServletResponse servletResponse = this.mockMvc
        .perform(request(httpMethod, uri).content(requestBody).headers(requestHeaders))
        .andReturn()
        .getResponse();
    HttpStatus status = HttpStatus.valueOf(servletResponse.getStatus());
    byte[] body = servletResponse.getContentAsByteArray();
    MockClientHttpResponse clientResponse = new MockClientHttpResponse(body, status);
    clientResponse.getHeaders().putAll(getResponseHeaders(servletResponse));
    return clientResponse;
  }
  catch (Exception ex) {
    byte[] body = ex.toString().getBytes(StandardCharsets.UTF_8);
    return new MockClientHttpResponse(body, HttpStatus.INTERNAL_SERVER_ERROR);
  }
}
origin: spring-projects/spring-framework

@Test  // SPR-13079
public void deferredResultWithDelayedError() throws Exception {
  MvcResult mvcResult = this.mockMvc.perform(get("/1").param("deferredResultWithDelayedError", "true"))
      .andExpect(request().asyncStarted())
      .andReturn();
  this.mockMvc.perform(asyncDispatch(mvcResult))
      .andExpect(status().is5xxServerError())
      .andExpect(content().string("Delayed Error"));
}
origin: cloudfoundry/uaa

private String requestExpiringCode(String email, String token) throws Exception {
  MockHttpServletRequestBuilder resetPasswordPost = post("/password_resets")
      .accept(APPLICATION_JSON_VALUE)
      .contentType(MediaType.APPLICATION_JSON)
      .header("Authorization", "Bearer " + token)
      .content(email);
  MvcResult mvcResult = mockMvc.perform(resetPasswordPost)
      .andExpect(status().isCreated()).andReturn();
  return JsonUtils.readValue(mvcResult.getResponse().getContentAsString(),
      new TypeReference<Map<String, String>>() {
      }).get("code");
}
origin: spring-projects/spring-security

@Test
public void requestWhenJwtAuthenticationConverterCustomizedAuthoritiesThenThoseAuthoritiesArePropagated()
    throws Exception {
  this.spring.register(JwtDecoderConfig.class, CustomAuthorityMappingConfig.class, BasicController.class)
      .autowire();
  JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
  when(decoder.decode(JWT_TOKEN)).thenReturn(JWT);
  this.mvc.perform(get("/requires-read-scope")
      .with(bearerToken(JWT_TOKEN)))
      .andExpect(status().isOk());
}
origin: spring-projects/spring-framework

@Test
void springMvcTest(WebApplicationContext wac) throws Exception {
  webAppContextSetup(wac).build()
    .perform(get("/person/42").accept(MediaType.APPLICATION_JSON))
    .andExpect(status().isOk())
    .andExpect(jsonPath("$.name", is("Dilbert")));
}
origin: spring-projects/spring-framework

@Test
public void saveSpecial() throws Exception {
  this.mockMvc.perform(post("/people").param("name", "Andy"))
      .andExpect(status().isFound())
      .andExpect(redirectedUrl("/persons/Joe"))
      .andExpect(model().size(1))
      .andExpect(model().attributeExists("name"))
      .andExpect(flash().attributeCount(1))
      .andExpect(flash().attribute("message", "success!"));
}
origin: spring-projects/spring-security

/**
 * http@realm equivalent
 */
@Test
public void basicAuthenticationWhenUsingCustomRealmThenMatchesNamespace() throws Exception {
  this.spring.register(CustomHttpBasicConfig.class, UserConfig.class).autowire();
  this.mvc.perform(get("/")
      .with(httpBasic("user", "invalid")))
      .andExpect(status().isUnauthorized())
      .andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Custom Realm\""));
}
origin: spring-projects/spring-security

@Test
public void requestWhenRealmNameConfiguredThenUsesOnAccessDenied()
    throws Exception {
  this.spring.register(RealmNameConfiguredOnAccessDeniedHandler.class, JwtDecoderConfig.class).autowire();
  JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
  when(decoder.decode(anyString())).thenReturn(JWT);
  this.mvc.perform(get("/authenticated")
      .with(bearerToken("insufficiently_scoped")))
      .andExpect(status().isForbidden())
      .andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer realm=\"myRealm\"")));
}
origin: spring-projects/spring-framework

@Test
public void person() throws Exception {
  this.mockMvc.perform(get("/person/5").accept(MediaType.APPLICATION_JSON))
    .andDo(print())
    .andExpect(status().isOk())
    .andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
}
origin: spring-projects/spring-framework

@Test
public void testContentStringMatcher() throws Exception {
  this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN))
    .andExpect(content().string(containsString("world")));
}
origin: spring-projects/spring-security

@Test
public void getWhenAcceptHeaderIsApplicationXhtmlXmlThenRespondsWith302() throws Exception {
  this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
  this.mvc.perform(get("/")
      .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XHTML_XML))
      .andExpect(status().isFound());
}
origin: cloudfoundry/uaa

private void resetPassword(String defaultPassword) throws Exception {
  String code = getExpiringCode(null, null);
  MockHttpServletRequestBuilder post = post("/password_change")
    .header("Authorization", "Bearer " + loginToken)
    .contentType(APPLICATION_JSON)
    .content("{\"code\":\"" + code + "\",\"new_password\":\"" + defaultPassword + "\"}")
    .accept(APPLICATION_JSON);
  getMockMvc().perform(post)
    .andExpect(status().isOk())
    .andExpect(jsonPath("$.user_id").exists())
    .andExpect(jsonPath("$.username").value(user.getUserName()));
}
origin: spring-projects/spring-framework

  @Test
  public void testFeedWithLinefeedChars() throws Exception {

//        Map<String, String> namespace = Collections.singletonMap("ns", "");

    standaloneSetup(new BlogFeedController()).build()
      .perform(get("/blog.atom").accept(MediaType.APPLICATION_ATOM_XML))
        .andExpect(status().isOk())
        .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_ATOM_XML))
        .andExpect(xpath("//feed/title").string("Test Feed"))
        .andExpect(xpath("//feed/icon").string("http://www.example.com/favicon.ico"));
  }

origin: spring-projects/spring-security

@Test
public void getWhenDeclaringHttpBasicBeforeFormLoginThenRespondsWith401() throws Exception {
  this.spring.register(BasicAuthenticationEntryPointBeforeFormLoginConfig.class).autowire();
  this.mvc.perform(get("/")
      .header(HttpHeaders.ACCEPT, "bogus/type"))
      .andExpect(status().isUnauthorized());
}
origin: spring-projects/spring-framework

@Test
public void stringWithMatcherAndCorrectResponseHeaderValue() throws Exception {
  this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, minuteAgo))
      .andExpect(header().string(LAST_MODIFIED, equalTo(now)));
}
origin: cloudfoundry/uaa

  @Test
  public void changeEmail_withIncorrectCode() throws Exception {
    when(expiringCodeStore.retrieveCode("the_secret_code", IdentityZoneHolder.get().getId()))
      .thenReturn(new ExpiringCode("the_secret_code", new Timestamp(System.currentTimeMillis()), "{\"userId\":\"user-id-001\",\"email\":\"new@example.com\",\"client_id\":null}", "incorrect-code"));

    mockMvc.perform(post("/email_changes")
      .contentType(APPLICATION_JSON)
      .content("the_secret_code")
      .accept(APPLICATION_JSON))
      .andExpect(MockMvcResultMatchers.status().isUnprocessableEntity());
  }
}
org.springframework.test.web.servlet.requestMockHttpServletRequestBuilder

Javadoc

Default builder for MockHttpServletRequest required as input to perform requests in MockMvc.

Application tests will typically access this builder through the static factory methods in MockMvcRequestBuilders.

This class is not open for extension. To apply custom initialization to the created MockHttpServletRequest, please use the #with(RequestPostProcessor) extension point.

Most used methods

  • contentType
    Set the 'Content-Type' header of the request.
  • content
    Set the request body.
  • param
    Add a request parameter to the MockHttpServletRequest.If called more than once, new values get added
  • accept
    Set the 'Accept' header to the given media type(s).
  • header
    Add a header to the request. Values are always added.
  • with
    An extension point for further initialization of MockHttpServletRequestin ways not built directly in
  • requestAttr
    Set a request attribute.
  • buildRequest
    Build a MockHttpServletRequest.
  • contextPath
    Specify the portion of the requestURI that represents the context path. The context path, if specifi
  • principal
    Set the principal of the request.
  • flashAttr
    Set an "input" flash attribute.
  • headers
    Add all headers to the request. Values are always added.
  • flashAttr,
  • headers,
  • session,
  • sessionAttr,
  • cookie,
  • params,
  • servletPath,
  • <init>,
  • characterEncoding,
  • locale

Popular in Java

  • Making http post requests using okhttp
  • getSystemService (Context)
  • findViewById (Activity)
  • setContentView (Activity)
  • Color (java.awt)
    The Color class is used to encapsulate colors in the default sRGB color space or colors in arbitrary
  • Component (java.awt)
    A component is an object having a graphical representation that can be displayed on the screen and t
  • Timestamp (java.sql)
    A Java representation of the SQL TIMESTAMP type. It provides the capability of representing the SQL
  • Stream (java.util.stream)
    A sequence of elements supporting sequential and parallel aggregate operations. The following exampl
  • JTextField (javax.swing)
  • Project (org.apache.tools.ant)
    Central representation of an Ant project. This class defines an Ant project with all of its targets,
  • From CI to AI: The AI layer in your organization
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now