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

The following examples show how to use org.springframework.test.web.servlet.ResultMatcher. 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: ResponseBodyMatchers.java    From code-examples with 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
Source File: DataTypeControllerIntegrationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private ResultActions executeMoveAttribute(String typeCode, String attributeCode, boolean moveUp, String accessToken, ResultMatcher expected) throws Exception {
    String suffix = (moveUp) ? "moveUp" : "moveDown";
    ResultActions result = mockMvc
            .perform(put("/dataTypes/{dataTypeCode}/attribute/{attributeCode}/" + suffix, new Object[]{typeCode, attributeCode})
                    .content("{}")
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .header("Authorization", "Bearer " + accessToken));
    result.andExpect(expected);
    return result;
}
 
Example #3
Source File: RequestMapingShortcutsIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void giventUrl_whenGetRequest_thenFindGetResponse() throws Exception {

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

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

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

}
 
Example #4
Source File: DataTypeControllerIntegrationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private ResultActions executeDataTypeAttributeDelete(String typeCode,
        String attributeCode, String accessToken, ResultMatcher expected) throws Exception {
    ResultActions result = mockMvc
            .perform(delete("/dataTypes/{dataTypeCode}/attribute/{attributeCode}", new Object[]{typeCode, attributeCode})
                    .header("Authorization", "Bearer " + accessToken));
    result.andExpect(expected);
    return result;
}
 
Example #5
Source File: ModelResultMatchers.java    From spring4-understanding with 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 #6
Source File: GuiFragmentSettingsControllerIntegrationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private ResultActions executePut(String body, String accessToken, ResultMatcher rm) throws Exception {
    ResultActions result = mockMvc
            .perform(put("/fragmentsSettings").content(body)
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .header("Authorization", "Bearer " + accessToken));
    result.andExpect(rm);
    return result;
}
 
Example #7
Source File: ProfileTypeControllerIntegrationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private ResultActions executeProfileAttributePost(String fileName, String typeCode, String accessToken, ResultMatcher expected) throws Exception {
    InputStream isJsonPostValid = this.getClass().getResourceAsStream(fileName);
    String jsonPostValid = FileTextReader.getText(isJsonPostValid);
    ResultActions result = mockMvc
            .perform(post("/profileTypes/{profileTypeCode}/attribute", new Object[]{typeCode})
                    .content(jsonPostValid)
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .header("Authorization", "Bearer " + accessToken));
    result.andExpect(expected);
    return result;
}
 
Example #8
Source File: FlashAttributeResultMatchers.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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);
		}
	};
}
 
Example #9
Source File: ModelResultMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Assert a model attribute value.
 */
public ResultMatcher attribute(final String name, final Object value) {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) throws Exception {
			ModelAndView mav = getModelAndView(result);
			assertEquals("Model attribute '" + name + "'", value, mav.getModel().get(name));
		}
	};
}
 
Example #10
Source File: XpathResultMatchers.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Evaluate the XPath and assert the {@link Node} content found with the
 * given Hamcrest {@link Matcher}.
 */
public ResultMatcher node(final Matcher<? super Node> matcher) {
	return result -> {
		MockHttpServletResponse response = result.getResponse();
		this.xpathHelper.assertNode(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
	};
}
 
Example #11
Source File: HeaderResultMatchers.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Assert the values of the response header with the given Hamcrest
 * Iterable {@link Matcher}.
 * @since 4.3
 */
public <T> ResultMatcher stringValues(final String name, final Matcher<Iterable<String>> matcher) {
	return result -> {
		List<String> values = result.getResponse().getHeaders(name);
		assertThat("Response header '" + name + "'", values, matcher);
	};
}
 
Example #12
Source File: XpathResultMatchers.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Evaluate the XPath and assert the number of nodes found with the given
 * Hamcrest {@link Matcher}.
 */
public ResultMatcher nodeCount(final Matcher<Integer> matcher) {
	return result -> {
		MockHttpServletResponse response = result.getResponse();
		this.xpathHelper.assertNodeCount(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
	};
}
 
Example #13
Source File: XpathResultMatchers.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Evaluate the XPath and assert the number of nodes found.
 */
public ResultMatcher nodeCount(final int expectedCount) {
	return result -> {
		MockHttpServletResponse response = result.getResponse();
		this.xpathHelper.assertNodeCount(response.getContentAsByteArray(), getDefinedEncoding(response), expectedCount);
	};
}
 
Example #14
Source File: XpathResultMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate the XPath and assert the number of nodes found with the given
 * Hamcrest {@link Matcher}.
 */
public ResultMatcher nodeCount(final Matcher<Integer> matcher) {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) throws Exception {
			MockHttpServletResponse response = result.getResponse();
			xpathHelper.assertNodeCount(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
		}
	};
}
 
Example #15
Source File: ViewResultMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Assert the selected view name with the given Hamcrest {@link Matcher}.
 */
public ResultMatcher name(final Matcher<? super String> matcher) {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) throws Exception {
			ModelAndView mav = result.getModelAndView();
			assertTrue("No ModelAndView found", mav != null);
			assertThat("View name", mav.getViewName(), matcher);
		}
	};
}
 
Example #16
Source File: ModelResultMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Assert the given model attribute(s) have errors.
 */
public ResultMatcher attributeErrorCount(final String name, final int expectedCount) {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult result) throws Exception {
			ModelAndView mav = getModelAndView(result);
			Errors errors = getBindingResult(mav, name);
			assertEquals("Binding/validation error count for attribute [" + name + "], ",
					expectedCount, errors.getErrorCount());
		}
	};
}
 
Example #17
Source File: RequestResultMatchers.java    From java-technology-stack with 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 #18
Source File: MockMvcResultMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #19
Source File: CookieResultMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #20
Source File: UserProfileControllerIntegrationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #21
Source File: CookieResultMatchers.java    From java-technology-stack with 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 #22
Source File: RequestMapingShortcutsIntegrationTest.java    From tutorials with 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 #23
Source File: MockMvcResultMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 File: AbstractAirsonicRestApiJukeboxIntTest.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
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 #25
Source File: ModelResultMatchers.java    From spring4-understanding with 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 #26
Source File: JsonPathResultMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #27
Source File: ModelResultMatchers.java    From java-technology-stack with 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 #28
Source File: ModelResultMatchers.java    From spring-analysis-note with 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 #29
Source File: ModelResultMatchers.java    From spring-analysis-note with 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 #30
Source File: ModelResultMatchers.java    From spring-analysis-note with 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());
		}
	};
}