Java Code Examples for org.springframework.test.web.servlet.ResultMatcher

The following examples show how to use org.springframework.test.web.servlet.ResultMatcher. These examples are extracted from open source projects. 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 Project: code-examples   Source File: ResponseBodyMatchers.java    License: MIT License 6 votes vote down vote up
public ResultMatcher containsError(String expectedFieldName, String expectedMessage) {
  return mvcResult -> {
    String json = mvcResult.getResponse().getContentAsString();
    ErrorResult errorResult = objectMapper.readValue(json, ErrorResult.class);
    List<FieldValidationError> fieldErrors = errorResult.getFieldErrors().stream()
            .filter(fieldError -> fieldError.getField().equals(expectedFieldName))
            .filter(fieldError -> fieldError.getMessage().equals(expectedMessage))
            .collect(Collectors.toList());

    assertThat(fieldErrors)
            .hasSize(1)
            .withFailMessage("expecting exactly 1 error message with field name '%s' and message '%s'",
                    expectedFieldName,
                    expectedMessage);
  };
}
 
Example 2
private ResultMatcher playListItem1isCorrect() {
    MediaFile mediaFile = testJukeboxPlayer.getPlayQueue().getFile(0);
    MediaFile parent = mediaFileDao.getMediaFile(mediaFile.getParentPath());
    Album album = albumDao.getAlbum(mediaFile.getArtist(), mediaFile.getAlbumName());
    Artist artist = artistDao.getArtist(mediaFile.getArtist());
    assertThat(album).isNotNull();
    return result -> {
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].id").value(mediaFile.getId()).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].parent").value(parent.getId()).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].isDir").value(mediaFile.isDirectory()).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].title").value(mediaFile.getTitle()).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].album").value(mediaFile.getAlbumName()).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].artist").value(mediaFile.getArtist()).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].coverArt").value(parent.getId()).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].size").value(mediaFile.getFileSize()).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].contentType").value(StringUtil.getMimeType(mediaFile.getFormat())).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].suffix").value(mediaFile.getFormat()).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].duration").value(Math.round(mediaFile.getDuration())).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].bitRate").value(mediaFile.getBitRate()).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].path").value(SubsonicRESTController.getRelativePath(mediaFile, settingsService)).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].isVideo").value(mediaFile.isVideo()).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].playCount").isNumber().match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].created").value(convertInstantToString(mediaFile.getCreated())).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].albumId").value(album.getId()).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].artistId").value(artist.getId()).match(result);
        jsonPath("$.subsonic-response.jukeboxPlaylist.entry[0].type").value(mediaFile.getMediaType().name().toLowerCase()).match(result);
    };
}
 
Example 3
/**
 * Assert whether asynchronous processing started, usually as a result of a
 * controller method returning {@link Callable} or {@link DeferredResult}.
 * <p>The test will await the completion of a {@code Callable} so that
 * {@link #asyncResult(Matcher)} can be used to assert the resulting value.
 * Neither a {@code Callable} nor a {@code DeferredResult} will complete
 * processing all the way since a {@link MockHttpServletRequest} does not
 * perform asynchronous dispatches.
 */
public ResultMatcher asyncStarted() {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) {
			HttpServletRequest request = result.getRequest();
			assertAsyncStarted(request);
		}
	};
}
 
Example 4
/**
 * Assert a cookie's maxAge with a Hamcrest {@link Matcher}.
 */
public ResultMatcher maxAge(final String name, final Matcher<? super Integer> matcher) {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) {
			Cookie cookie = result.getResponse().getCookie(name);
			assertTrue("No cookie with name: " + name, cookie != null);
			assertThat("Response cookie maxAge", cookie.getMaxAge(), matcher);
		}
	};
}
 
Example 5
Source Project: java-technology-stack   Source File: XpathResultMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * Evaluate the XPath and assert that content doesn't exist.
 */
public ResultMatcher doesNotExist() {
	return result -> {
		MockHttpServletResponse response = result.getResponse();
		this.xpathHelper.doesNotExist(response.getContentAsByteArray(), getDefinedEncoding(response));
	};
}
 
Example 6
private ResultActions executeUpdatePageStatus(String pageCode,
        PageStatusRequest statusRequest, String accessToken, ResultMatcher expected) throws Exception {
    ResultActions result = mockMvc
                .perform(put("/pages/{pageCode}/status", pageCode)
                        .content(mapper.writeValueAsString(statusRequest))
                        .contentType(MediaType.APPLICATION_JSON)
                        .header("Authorization", "Bearer " + accessToken));
    result.andExpect(expected);
    return result;
}
 
Example 7
/**
 * Assert the response status code is equal to an integer value.
 */
public ResultMatcher is(final int status) {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) throws Exception {
			assertEquals("Response status", status, result.getResponse().getStatus());
		}
	};
}
 
Example 8
Source Project: spring-analysis-note   Source File: CookieResultMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * Assert a cookie's version with a Hamcrest {@link Matcher}.
 */
public ResultMatcher version(final String name, final Matcher<? super Integer> matcher) {
	return result -> {
		Cookie cookie = getCookie(result, name);
		assertThat("Response cookie '" + name + "' version", cookie.getVersion(), matcher);
	};
}
 
Example 9
/**
 * Assert the response status code is in the 3xx range.
 */
public ResultMatcher is3xxRedirection() {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) throws Exception {
			assertEquals("Range for response status value " + result.getResponse().getStatus(),
					HttpStatus.Series.REDIRECTION, getHttpStatusSeries(result));
		}
	};
}
 
Example 10
Source Project: java-technology-stack   Source File: ModelResultMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * Assert the given model attribute(s) have errors.
 */
public ResultMatcher attributeHasErrors(final String... names) {
	return mvcResult -> {
		ModelAndView mav = getModelAndView(mvcResult);
		for (String name : names) {
			BindingResult result = getBindingResult(mav, name);
			assertTrue("No errors for attribute '" + name + "'", result.hasErrors());
		}
	};
}
 
Example 11
Source Project: spring-boot-rest-example   Source File: HotelControllerTest.java    License: MIT License 5 votes vote down vote up
private static ResultMatcher redirectedUrlPattern(final String expectedUrlPattern) {
    return new ResultMatcher() {
        public void match(MvcResult result) {
            Pattern pattern = Pattern.compile("\\A" + expectedUrlPattern + "\\z");
            assertTrue(pattern.matcher(result.getResponse().getRedirectedUrl()).find());
        }
    };
}
 
Example 12
Source Project: coderadar   Source File: ResultMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * Tests if the response contains the JSON representation of an object of the given type.
 *
 * @param clazz the class of the expected object.
 * @param <T> the type of the expected object.
 * @return ResultMatcher that performs the test described above.
 */
public static <T> ResultMatcher containsResource(Class<T> clazz) {
  return result -> {
    String json = result.getResponse().getContentAsString();
    try {
      T object = fromJson(json, clazz);
      AssertionsForClassTypes.assertThat(object).isNotNull();
    } catch (Exception e) {
      throw new RuntimeException(
          String.format("expected JSON representation of class %s but found '%s'", clazz, json),
          e);
    }
  };
}
 
Example 13
Source Project: java-technology-stack   Source File: ModelResultMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * Assert a field error code for a model attribute using exact String match.
 * @since 4.1
 */
public ResultMatcher attributeHasFieldErrorCode(final String name, final String fieldName, final String error) {
	return mvcResult -> {
		ModelAndView mav = getModelAndView(mvcResult);
		BindingResult result = getBindingResult(mav, name);
		assertTrue("No errors for attribute '" + name + "'", result.hasErrors());
		FieldError fieldError = result.getFieldError(fieldName);
		if (fieldError == null) {
			fail("No errors for field '" + fieldName + "' of attribute '" + name + "'");
		}
		String code = fieldError.getCode();
		assertTrue("Expected error code '" + error + "' but got '" + code + "'", error.equals(code));
	};
}
 
Example 14
Source Project: spring-analysis-note   Source File: ModelResultMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * Assert a model attribute value with the given Hamcrest {@link Matcher}.
 */
@SuppressWarnings("unchecked")
public <T> ResultMatcher attribute(final String name, final Matcher<T> matcher) {
	return result -> {
		ModelAndView mav = getModelAndView(result);
		assertThat("Model attribute '" + name + "'", (T) mav.getModel().get(name), matcher);
	};
}
 
Example 15
/**
 * Assert the response status code is in the 5xx range.
 */
public ResultMatcher is5xxServerError() {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) throws Exception {
			assertEquals("Range for response status value " + result.getResponse().getStatus(),
					HttpStatus.Series.SERVER_ERROR, getHttpStatusSeries(result));
		}
	};
}
 
Example 16
Source Project: spring-analysis-note   Source File: ModelResultMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * Assert the given model attribute(s) have errors.
 */
public ResultMatcher attributeHasErrors(final String... names) {
	return mvcResult -> {
		ModelAndView mav = getModelAndView(mvcResult);
		for (String name : names) {
			BindingResult result = getBindingResult(mav, name);
			assertTrue("No errors for attribute '" + name + "'", result.hasErrors());
		}
	};
}
 
Example 17
Source Project: spring-analysis-note   Source File: ModelResultMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * Assert the given model attribute field(s) have errors.
 */
public ResultMatcher attributeHasFieldErrors(final String name, final String... fieldNames) {
	return mvcResult -> {
		ModelAndView mav = getModelAndView(mvcResult);
		BindingResult result = getBindingResult(mav, name);
		assertTrue("No errors for attribute '" + name + "'", result.hasErrors());
		for (final String fieldName : fieldNames) {
			boolean hasFieldErrors = result.hasFieldErrors(fieldName);
			assertTrue("No errors for field '" + fieldName + "' of attribute '" + name + "'", hasFieldErrors);
		}
	};
}
 
Example 18
Source Project: spring-analysis-note   Source File: ModelResultMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * Assert a field error code for a model attribute using exact String match.
 * @since 4.1
 */
public ResultMatcher attributeHasFieldErrorCode(final String name, final String fieldName, final String error) {
	return mvcResult -> {
		ModelAndView mav = getModelAndView(mvcResult);
		BindingResult result = getBindingResult(mav, name);
		assertTrue("No errors for attribute '" + name + "'", result.hasErrors());
		FieldError fieldError = result.getFieldError(fieldName);
		if (fieldError == null) {
			fail("No errors for field '" + fieldName + "' of attribute '" + name + "'");
		}
		String code = fieldError.getCode();
		assertTrue("Expected error code '" + error + "' but got '" + code + "'", error.equals(code));
	};
}
 
Example 19
Source Project: java-technology-stack   Source File: ModelResultMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * Assert the given model attribute(s) do not have errors.
 */
public ResultMatcher attributeHasNoErrors(final String... names) {
	return mvcResult -> {
		ModelAndView mav = getModelAndView(mvcResult);
		for (String name : names) {
			BindingResult result = getBindingResult(mav, name);
			assertTrue("Unexpected errors for attribute '" + name + "': " + result.getAllErrors(),
					!result.hasErrors());
		}
	};
}
 
Example 20
/**
 * Evaluate the JSON path expression against the response content and
 * assert that the result is a {@link Boolean}.
 * @since 4.2.1
 */
public ResultMatcher isBoolean() {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) throws Exception {
			String content = result.getResponse().getContentAsString();
			jsonPathHelper.assertValueIsBoolean(content);
		}
	};
}
 
Example 21
Source Project: spring4-understanding   Source File: ModelResultMatchers.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Assert the model has errors.
 */
public <T> ResultMatcher hasErrors() {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) throws Exception {
			int count = getErrorCount(getModelAndView(result).getModelMap());
			assertTrue("Expected binding/validation errors", count != 0);
		}
	};
}
 
Example 22
Source Project: spring4-understanding   Source File: ModelResultMatchers.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Assert the given model attribute(s) do not have errors.
 */
public ResultMatcher attributeHasNoErrors(final String... names) {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult mvcResult) throws Exception {
			ModelAndView mav = getModelAndView(mvcResult);
			for (String name : names) {
				BindingResult result = getBindingResult(mav, name);
				assertTrue("No errors for attribute [" + name + "]", !result.hasErrors());
			}
		}
	};
}
 
Example 23
/**
 * Asserts the request was redirected to the given URL.
 * <p>This methods accepts only exact matches.
 * @param expectedUrl the exact URL expected
 */
public static ResultMatcher redirectedUrl(final String expectedUrl) {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) {
			assertEquals("Redirected URL", expectedUrl, result.getResponse().getRedirectedUrl());
		}
	};
}
 
Example 24
Source Project: tutorials   Source File: RequestMapingShortcutsIntegrationTest.java    License: MIT License 5 votes vote down vote up
@Test
public void giventUrl_whenPostRequest_thenFindPostResponse() throws Exception {

    MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/post");

    ResultMatcher contentMatcher = MockMvcResultMatchers.content()
        .string("POST Response");

    this.mockMvc.perform(builder)
        .andExpect(contentMatcher)
        .andExpect(MockMvcResultMatchers.status()
            .isOk());

}
 
Example 25
Source Project: java-technology-stack   Source File: CookieResultMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * Assert a cookie path with a Hamcrest {@link Matcher}.
 */
public ResultMatcher path(final String name, final Matcher<? super String> matcher) {
	return result -> {
		Cookie cookie = getCookie(result, name);
		assertThat("Response cookie '" + name + "' path", cookie.getPath(), matcher);
	};
}
 
Example 26
private ResultActions executeProfileGet(String username, String accessToken, ResultMatcher expected) throws Exception {
    ResultActions result = mockMvc
            .perform(get("/userProfiles/{username}", new Object[]{username})
                    .header("Authorization", "Bearer " + accessToken));
    result.andExpect(expected);
    return result;
}
 
Example 27
/**
 * Assert a cookie exists. The existence check is irrespective of whether
 * max age is 0 (i.e. expired).
 */
public ResultMatcher exists(final String name) {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) {
			Cookie cookie = result.getResponse().getCookie(name);
			assertTrue("No cookie with name: " + name, cookie != null);
		}
	};
}
 
Example 28
/**
 * Asserts the request was forwarded to the given URL.
 * <p>This methods accepts only exact matches.
 * @param expectedUrl the exact URL expected
 */
public static ResultMatcher forwardedUrl(final String expectedUrl) {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) {
			assertEquals("Forwarded URL", expectedUrl, result.getResponse().getForwardedUrl());
		}
	};
}
 
Example 29
Source Project: java-technology-stack   Source File: RequestResultMatchers.java    License: MIT License 5 votes vote down vote up
/**
 * Assert the result from asynchronous processing with the given matcher.
 * <p>This method can be used when a controller method returns {@link Callable}
 * or {@link WebAsyncTask}.
 */
@SuppressWarnings("unchecked")
public <T> ResultMatcher asyncResult(final Matcher<T> matcher) {
	return result -> {
		HttpServletRequest request = result.getRequest();
		assertAsyncStarted(request);
		assertThat("Async result", (T) result.getAsyncResult(), matcher);
	};
}
 
Example 30
/**
 * Assert the existence of the given flash attributes.
 */
public <T> ResultMatcher attributeExists(final String... names) {
	return result -> {
		for (String name : names) {
			assertTrue("Flash attribute '" + name + "' does not exist", result.getFlashMap().get(name) != null);
		}
	};
}