Java Code Examples for org.springframework.test.web.servlet.ResultActions#andReturn()

The following examples show how to use org.springframework.test.web.servlet.ResultActions#andReturn() . 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: SpringTestAPITest.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void showXMLSourceWorksOnBasicTest() throws Exception {

	// Obtaining response and basic tests
	ResultActions resultActions = this.mvc
			//
			.perform(get("/test?showXMLSource=true"))
			//
			.andDo(print())
			//
			.andExpect(status().isOk())
			.andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_XML))
			//
			;
	// Check the XML
	resultActions.andExpect(xpath("/app/pojos/pojo").exists());
	//
	MvcResult response = resultActions.andReturn();
	// Check the model is still there
	final Object model = response.getModelAndView().getModel().get(XsltConfiguration.XML_SOURCE_TAG);
	assertNotNull("Model object returned is not null", model);
	assertThat("Model object is of the appropriate class", model, instanceOf(App.class));
}
 
Example 2
Source File: TestSupportWithMVC.java    From rebuild with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param builder
 * @param user
 * @param expect
 * @return
 * @throws Exception
 */
protected MvcResponse perform(MockHttpServletRequestBuilder builder, ID user, ResultMatcher expect) throws Exception {
    builder.contentType("text/plain; charset=utf-8")
            .accept(MediaType.APPLICATION_JSON_UTF8)
            .header(HttpHeaders.USER_AGENT, UA_WIN10_CHROME);
    if (user != null) {
        builder.sessionAttr(WebUtils.CURRENT_USER, user);
    }

    ResultActions resultActions = springMVC.perform(builder);
    if (expect == null) {
        resultActions.andExpect(MockMvcResultMatchers.status().isOk());
    } else {
        resultActions.andExpect(expect);
    }

    MvcResult result = resultActions.andReturn();

    String content = result.getResponse().getContentAsString();
    if (StringUtils.isNotBlank(content)) {
        return new MvcResponse(content);
    }

    ModelAndView view = result.getModelAndView();
    return new MvcResponse(view);
}
 
Example 3
Source File: WelcomeControllerTest.java    From spring-boot with MIT License 5 votes vote down vote up
@Test
public void main() throws Exception {
    ResultActions resultActions = mockMvc.perform(get("/"))
            .andExpect(status().isOk())
            .andExpect(view().name("welcome"))
            .andExpect(model().attribute("message", equalTo("Mkyong")))
            .andExpect(model().attribute("tasks", is(expectedList)))
            .andExpect(content().string(containsString("Hello, Mkyong")));

    MvcResult mvcResult = resultActions.andReturn();
    ModelAndView mv = mvcResult.getModelAndView();
    //
}
 
Example 4
Source File: ExceptionHandlerInstrumentationWithGlobalAdviceTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testExceptionCaptureWithGlobalControllerAdvice() throws Exception {

    ResultActions resultActions = this.mockMvc.perform(get("/controller-advice/throw-exception"));
    MvcResult result = resultActions.andReturn();
    MockHttpServletResponse response = result.getResponse();

    assertExceptionCapture(ControllerAdviceRuntimeException.class, response, 409, "controller-advice runtime exception occurred", "runtime exception occurred");
}
 
Example 5
Source File: ExceptionHandlerInstrumentationWithGlobalAdviceTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testExceptionCaptureWithGlobalControllerAdvice_StatusCode200() throws Exception {

    ResultActions resultActions = this.mockMvc.perform(get("/controller-advice/throw-exception-sc200"));
    MvcResult result = resultActions.andReturn();
    MockHttpServletResponse response = result.getResponse();

    assertExceptionCapture(ControllerAdviceRuntimeException200.class, response, 200, "controller-advice runtime exception occurred", "runtime exception occurred");
}
 
Example 6
Source File: ExceptionHandlerInstrumentationWithExceptionResolverTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testCallApiWithExceptionThrown() throws Exception {
    ResultActions resultActions = this.mockMvc.perform(get("/exception-resolver/throw-exception"));
    MvcResult result = resultActions.andReturn();
    MockHttpServletResponse response = result.getResponse();

    assertExceptionCapture(ExceptionResolverRuntimeException.class, response, 200, "", "runtime exception occurred");
    assertEquals("error-page", response.getForwardedUrl());
    assertEquals("runtime exception occurred", result.getModelAndView().getModel().get("message"));
}
 
Example 7
Source File: ExceptionHandlerInstrumentationWithExceptionHandlerTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testExceptionCapture() throws Exception {
    ResultActions resultActions = this.mockMvc.perform(get("/exception-handler/throw-exception"));
    MvcResult result = resultActions.andReturn();
    MockHttpServletResponse response = result.getResponse();

    assertExceptionCapture(ExceptionHandlerRuntimeException.class, response, 409, "exception-handler runtime exception occurred", "runtime exception occurred");
}
 
Example 8
Source File: ExceptionHandlerInstrumentationWithExceptionHandlerTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testExceptionCapture_StatusCode200() throws Exception {
    ResultActions resultActions = this.mockMvc.perform(get("/exception-handler/throw-exception-sc200"));
    MvcResult result = resultActions.andReturn();
    MockHttpServletResponse response = result.getResponse();

    assertExceptionCapture(ExceptionHandlerRuntimeException200.class, response, 200, "exception-handler runtime exception occurred", "runtime exception occurred");
}
 
Example 9
Source File: FreeMarkerViewTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testViewRender() throws Exception {
    ResultActions resultActions = mockMvc.perform(get("/free-marker"));

    MvcResult mvcResult = resultActions.andReturn();

    verifySpanCapture("FreeMarker", " example", mvcResult.getResponse(), "FreeMarker Template example: Message 123");
}
 
Example 10
Source File: JspViewTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testViewRender() throws Exception {
    ResultActions resultActions = mockMvc.perform(get("/jsp"));
    MvcResult mvcResult = resultActions.andReturn();

    verifySpanCapture("InternalResource", " message-view", mvcResult.getResponse(), "");

    ModelAndView modelAndView = mvcResult.getModelAndView();
    assertEquals(modelAndView.getModel().get("message"), "Message 123");
}
 
Example 11
Source File: Jade4jTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testViewRender() throws Exception {
    ResultActions resultActions = mockMvc.perform(get("/jade4j"));

    MvcResult mvcResult = resultActions.andReturn();
    verifySpanCapture("Jade", " hello", mvcResult.getResponse(), "<!DOCTYPE html><html><body><Hello>Message 123</Hello></body></html>");
}
 
Example 12
Source File: GroovyTemplateTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testViewRender() throws Exception {
    ResultActions resultActions = mockMvc.perform(get("/groovy"));

    MvcResult mvcResult = resultActions.andReturn();

    verifySpanCapture("GroovyMarkup", " hello", mvcResult.getResponse(), "<!DOCTYPE html><html lang='en'><head><meta http-equiv='\"Content-Type\" content=\"text/html; charset=utf-8\"'/><title>My page</title></head><body><h2>A Groovy View with Spring MVC</h2><div>msg: Message 123</div></body></html>");
}
 
Example 13
Source File: Jackson2JsonViewTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testViewRender() throws Exception {
    ResultActions resultActions = mockMvc.perform(get("/jackson"));

    MvcResult mvcResult = resultActions.andReturn();
    verifySpanCapture("MappingJackson2Json", " jsonTemplate", mvcResult.getResponse(), "{\n  \"message\" : \"Message 123\"\n}");
}
 
Example 14
Source File: ThymeleafTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testViewRender() throws Exception {
    ResultActions resultActions = mockMvc.perform(get("/thymeleaf"));

    MvcResult mvcResult = resultActions.andReturn();

    verifySpanCapture("Thymeleaf", "", mvcResult.getResponse(), "<span>Message 123</span>");
}
 
Example 15
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 16
Source File: ExceptionHandlerInstrumentationWithResponseStatusExceptionTest.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testCallApiWithExceptionThrown() throws Exception {

    ResultActions resultActions = this.mockMvc.perform(get("/response-status-exception/throw-exception"));
    MvcResult result = resultActions.andReturn();
    MockHttpServletResponse response = result.getResponse();

    assertExceptionCapture(ResponseStatusException.class, response, 409, "", "Response status 409 with reason \"responseStatusException\"; nested exception is co.elastic.apm.agent.spring.webmvc.exception.testapp.response_status_exception.ResponseStatusRuntimeException: runtime exception occurred");
    assertEquals("runtime exception occurred", reporter.getErrors().get(0).getException().getCause().getMessage());
    assertEquals(ResponseStatusRuntimeException.class, reporter.getErrors().get(0).getException().getCause().getClass());
}