Java Code Examples for org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder#content()

The following examples show how to use org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder#content() . 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: BaseControllerTest.java    From spring-boot-vue-admin with Apache License 2.0 6 votes vote down vote up
private Result execute(
    final HttpMethod method, final String targetUrl, final Object args, final String token)
    throws Exception {
  final MockHttpServletRequestBuilder builders =
      MockMvcRequestBuilders.request(method, targetUrl)
          .contentType(MediaType.APPLICATION_JSON_UTF8);
  if (args != null) {
    builders.content(JSON.toJSONString(args));
  }
  if (StringUtils.isNotBlank(token)) {
    builders.header("Authorization", token);
  }
  return JSON.parseObject(
      this.mockMvc
          .perform(builders)
          .andDo(print())
          .andExpect(status().isOk())
          .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
          .andReturn()
          .getResponse()
          .getContentAsString(),
      Result.class);
}
 
Example 2
Source File: JobConfigControllerTestIT.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Test
@WithMockUser(roles = AlertIntegrationTest.ROLE_ALERT_ADMIN)
public void testSaveConfig() throws Exception {
    addGlobalConfiguration(blackDuckProviderKey, Map.of(
        BlackDuckDescriptor.KEY_BLACKDUCK_URL, List.of("BLACKDUCK_URL"),
        BlackDuckDescriptor.KEY_BLACKDUCK_API_KEY, List.of("BLACKDUCK_API")));
    MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post(url)
                                                .with(SecurityMockMvcRequestPostProcessors.user("admin").roles(AlertIntegrationTest.ROLE_ALERT_ADMIN))
                                                .with(SecurityMockMvcRequestPostProcessors.csrf());

    JobFieldModel fieldModel = createTestJobFieldModel(null, null);

    request.content(gson.toJson(fieldModel));
    request.contentType(contentType);

    MvcResult mvcResult = mockMvc.perform(request).andExpect(MockMvcResultMatchers.status().isCreated()).andReturn();
    String response = mvcResult.getResponse().getContentAsString();

    checkResponse(response);
}
 
Example 3
Source File: JobConfigControllerTestIT.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Test
@WithMockUser(roles = AlertIntegrationTest.ROLE_ALERT_ADMIN)
public void testValidateConfig() throws Exception {
    final String urlPath = url + "/validate";
    addGlobalConfiguration(blackDuckProviderKey, Map.of(
        BlackDuckDescriptor.KEY_BLACKDUCK_URL, List.of("BLACKDUCK_URL"),
        BlackDuckDescriptor.KEY_BLACKDUCK_API_KEY, List.of("BLACKDUCK_API")));
    MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post(urlPath)
                                                .with(SecurityMockMvcRequestPostProcessors.user("admin").roles(AlertIntegrationTest.ROLE_ALERT_ADMIN))
                                                .with(SecurityMockMvcRequestPostProcessors.csrf());

    JobFieldModel fieldModel = createTestJobFieldModel(null, null);

    request.content(gson.toJson(fieldModel));
    request.contentType(contentType);

    mockMvc.perform(request).andExpect(MockMvcResultMatchers.status().isOk());
}
 
Example 4
Source File: ContentModelControllerUnitTest.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
private ResultActions performRequest(MockHttpServletRequestBuilder requestBuilder, String payload) throws Exception {

        UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
        String accessToken = mockOAuthInterceptor(user);

        requestBuilder = requestBuilder
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .header("Authorization", "Bearer " + accessToken);

        if (payload != null) {
            requestBuilder = requestBuilder.content(payload);
        }

        ResultActions result = mockMvc.perform(requestBuilder);

        return result;
    }
 
Example 5
Source File: SystemControllerTestIT.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
@Test
@WithMockUser(roles = AlertIntegrationTest.ROLE_ALERT_ADMIN)
public void testPostInitialSystemSetup() throws Exception {
    final HashMap<String, FieldValueModel> valueModelMap = new HashMap<>();
    final FieldModel configuration = new FieldModel("a_key", ConfigContextEnum.GLOBAL.name(), valueModelMap);

    final MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post(SYSTEM_INITIAL_SETUP_BASE_URL)
                                                      .with(SecurityMockMvcRequestPostProcessors.user("admin").roles(AlertIntegrationTest.ROLE_ALERT_ADMIN))
                                                      .with(SecurityMockMvcRequestPostProcessors.csrf());
    request.content(gson.toJson(configuration));
    request.contentType(contentType);
    mockMvc.perform(request).andExpect(MockMvcResultMatchers.status().isNotFound());
}
 
Example 6
Source File: AuthenticationControllerTestIT.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
@Test
public void testLogin() throws Exception {
    MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post(loginUrl);
    TestProperties testProperties = new TestProperties();
    MockLoginRestModel mockLoginRestModel = new MockLoginRestModel();
    mockLoginRestModel.setBlackDuckUsername(testProperties.getProperty(TestPropertyKey.TEST_BLACKDUCK_PROVIDER_USERNAME));
    mockLoginRestModel.setBlackDuckPassword(testProperties.getProperty(TestPropertyKey.TEST_BLACKDUCK_PROVIDER_PASSWORD));

    ReflectionTestUtils.setField(alertProperties, "alertTrustCertificate", Boolean.valueOf(testProperties.getProperty(TestPropertyKey.TEST_BLACKDUCK_PROVIDER_TRUST_HTTPS_CERT)));
    String restModel = mockLoginRestModel.getRestModelJson();
    request.content(restModel);
    request.contentType(contentType);
    mockMvc.perform(request).andExpect(MockMvcResultMatchers.status().isOk());
}
 
Example 7
Source File: JobConfigControllerTestIT.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
@Test
@WithMockUser(roles = AlertIntegrationTest.ROLE_ALERT_ADMIN)
public void testUpdateConfig() throws Exception {
    JobFieldModel fieldModel = createTestJobFieldModel("1", "2");
    Map<String, Collection<String>> fieldValueModels = new HashMap<>();
    for (FieldModel newFieldModel : fieldModel.getFieldModels()) {
        fieldValueModels.putAll(newFieldModel.getKeyToValues().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().getValues())));
    }
    ConfigurationJobModel emptyConfigurationModel = addJob(slackChannelKey.getUniversalKey(), blackDuckProviderKey.getUniversalKey(), fieldValueModels);
    addGlobalConfiguration(blackDuckProviderKey, Map.of(
        BlackDuckDescriptor.KEY_BLACKDUCK_URL, List.of("BLACKDUCK_URL"),
        BlackDuckDescriptor.KEY_BLACKDUCK_API_KEY, List.of("BLACKDUCK_API")));
    String configId = String.valueOf(emptyConfigurationModel.getJobId());
    String urlPath = url + "/" + configId;
    MockHttpServletRequestBuilder request = MockMvcRequestBuilders.put(urlPath)
                                                .with(SecurityMockMvcRequestPostProcessors.user("admin").roles(AlertIntegrationTest.ROLE_ALERT_ADMIN))
                                                .with(SecurityMockMvcRequestPostProcessors.csrf());

    fieldModel.setJobId(configId);

    request.content(gson.toJson(fieldModel));
    request.contentType(contentType);

    MvcResult mvcResult = mockMvc.perform(request).andExpect(MockMvcResultMatchers.status().isAccepted()).andReturn();
    String response = mvcResult.getResponse().getContentAsString();
    checkResponse(response);
}
 
Example 8
Source File: SpringMockMvcUtil.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public static <B extends Message, E extends Message> Optional<E> doPost(MockMvc mockMvc,
                                                                        String path,
                                                                        Optional<B> bodyOptional,
                                                                        Optional<Class<E>> entityTypeOptional,
                                                                        Optional<String[]> queryParametersOptional) throws Exception {

    MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path)
            .contentType(MediaType.APPLICATION_JSON)
            .characterEncoding("UTF-8")
            .principal(JUNIT_AUTHENTICATION);

    if (queryParametersOptional.isPresent()) {
        String[] queryParameters = queryParametersOptional.get();
        for (int i = 0; i < queryParameters.length; i += 2) {
            requestBuilder.queryParam(queryParameters[i], queryParameters[i + 1]);
        }
    }

    if (bodyOptional.isPresent()) {
        requestBuilder.content(JsonFormat.printer().print(bodyOptional.get()));
    }

    ResultActions resultActions = mockMvc.perform(requestBuilder)
            .andDo(print())
            .andExpect(r -> {
                int status = r.getResponse().getStatus();
                assertThat(status / 100 == 2).describedAs("2xx expected for POST, not: " + status).isTrue();
            });
    if (entityTypeOptional.isPresent()) {
        resultActions.andExpect(content().contentType(MediaType.APPLICATION_JSON));
    }
    MvcResult mvcResult = resultActions.andReturn();

    if (entityTypeOptional.isPresent()) {
        Message.Builder builder = newBuilder(entityTypeOptional.get());
        JsonFormat.parser().merge(mvcResult.getResponse().getContentAsString(), builder);
        return Optional.of((E) builder.build());
    }
    return Optional.empty();
}
 
Example 9
Source File: MockMvcHelper.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * receives a MockHttpServletRequestBuilder and an Object, puts the string representation of the object into the MockHttpServletRequestBuilder
 *
 * @param contentBody    the object to stringify and write into the request builder
 * @param requestBuilder the MockHttpServletRequestBuilder to which add headers
 * @return the MockHttpServletRequestBuilder with standard headers
 */
private MockHttpServletRequestBuilder addBodyContent(MockHttpServletRequestBuilder requestBuilder, Object contentBody) throws JsonProcessingException {

    if (null != contentBody) {
        requestBuilder.content(this.objectMapper.writeValueAsString(contentBody));
    }

    return requestBuilder;
}