Polishing

(cherry picked from commit 430180a)
This commit is contained in:
Juergen Hoeller 2016-08-26 18:33:13 +02:00
parent b84fefc430
commit dfdfd72a3e
10 changed files with 115 additions and 116 deletions

View File

@ -66,7 +66,6 @@ public class GenericMessagingTemplateTests {
@Test
public void sendAndReceive() {
SubscribableChannel channel = new ExecutorSubscribableChannel(this.executor);
channel.subscribe(new MessageHandler() {
@Override
@ -82,8 +81,7 @@ public class GenericMessagingTemplateTests {
@Test
public void sendAndReceiveTimeout() throws InterruptedException {
final AtomicReference<Throwable> failure = new AtomicReference<>();
final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(1);
this.template.setReceiveTimeout(1);
@ -118,8 +116,9 @@ public class GenericMessagingTemplateTests {
assertNull(this.template.convertSendAndReceive(channel, "request", String.class));
assertTrue(latch.await(1000, TimeUnit.MILLISECONDS));
if (failure.get() != null) {
throw new AssertionError(failure.get());
Throwable ex = failure.get();
if (ex != null) {
throw new AssertionError(ex);
}
}
@ -138,6 +137,7 @@ public class GenericMessagingTemplateTests {
assertFalse(accessor.isMutable());
}
private class TestDestinationResolver implements DestinationResolver<MessageChannel> {
@Override
@ -145,4 +145,5 @@ public class GenericMessagingTemplateTests {
return messageChannel;
}
}
}

View File

@ -42,7 +42,9 @@ import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.handler.DestinationPatternsMessageCondition;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.handler.annotation.support.DestinationVariableMethodArgumentResolver;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
@ -54,9 +56,6 @@ import org.springframework.util.MimeType;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
import static org.springframework.messaging.handler.DestinationPatternsMessageCondition.*;
import static org.springframework.messaging.handler.annotation.support.DestinationVariableMethodArgumentResolver.*;
import static org.springframework.messaging.support.MessageHeaderAccessor.*;
/**
* Test fixture for {@link SendToMethodReturnValueHandlerTests}.
@ -357,7 +356,8 @@ public class SendToMethodReturnValueHandlerTests {
verify(messagingTemplate).convertAndSend(eq("/topic/dest"), eq(PAYLOAD), captor.capture());
MessageHeaders headers = captor.getValue();
SimpMessageHeaderAccessor accessor = getAccessor(headers, SimpMessageHeaderAccessor.class);
SimpMessageHeaderAccessor accessor =
MessageHeaderAccessor.getAccessor(headers, SimpMessageHeaderAccessor.class);
assertNotNull(accessor);
assertTrue(accessor.isMutable());
assertEquals("sess1", accessor.getSessionId());
@ -399,7 +399,7 @@ public class SendToMethodReturnValueHandlerTests {
SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create();
accessor.setSessionId(sessionId);
accessor.setSubscriptionId("sub1");
accessor.setHeader(DESTINATION_TEMPLATE_VARIABLES_HEADER, vars);
accessor.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars);
Message<?> message = MessageBuilder.createMessage(PAYLOAD, accessor.getMessageHeaders());
this.handler.handleReturnValue(PAYLOAD, this.sendToWithPlaceholdersReturnType, message);
@ -549,7 +549,7 @@ public class SendToMethodReturnValueHandlerTests {
headerAccessor.setSubscriptionId(subsId);
if (dest != null && destPrefix != null) {
headerAccessor.setDestination(destPrefix + dest);
headerAccessor.setHeader(LOOKUP_DESTINATION_HEADER, dest);
headerAccessor.setHeader(DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER, dest);
}
if (user != null) {
headerAccessor.setUser(user);
@ -563,6 +563,64 @@ public class SendToMethodReturnValueHandlerTests {
}
@SuppressWarnings("unused")
String handleNoAnnotations() {
return PAYLOAD;
}
@SendTo
@SuppressWarnings("unused")
String handleAndSendToDefaultDestination() {
return PAYLOAD;
}
@SendTo({"/dest1", "/dest2"})
@SuppressWarnings("unused")
String handleAndSendTo() {
return PAYLOAD;
}
@SendTo("/topic/chat.message.filtered.{roomName}")
@SuppressWarnings("unused")
String handleAndSendToWithPlaceholders() {
return PAYLOAD;
}
@SendToUser
@SuppressWarnings("unused")
String handleAndSendToUserDefaultDestination() {
return PAYLOAD;
}
@SendToUser(broadcast = false)
@SuppressWarnings("unused")
String handleAndSendToUserDefaultDestinationSingleSession() {
return PAYLOAD;
}
@SendToUser({"/dest1", "/dest2"})
@SuppressWarnings("unused")
String handleAndSendToUser() {
return PAYLOAD;
}
@SendToUser(destinations = { "/dest1", "/dest2" }, broadcast = false)
@SuppressWarnings("unused")
String handleAndSendToUserSingleSession() {
return PAYLOAD;
}
@JsonView(MyJacksonView1.class)
@SuppressWarnings("unused")
JacksonViewBean handleAndSendToJsonView() {
JacksonViewBean payload = new JacksonViewBean();
payload.setWithView1("with");
payload.setWithView2("with");
payload.setWithoutView("without");
return payload;
}
private static class TestUser implements Principal {
public String getName() {
@ -574,6 +632,7 @@ public class SendToMethodReturnValueHandlerTests {
}
}
private static class UniqueUser extends TestUser implements DestinationUserNameProvider {
@Override
@ -582,6 +641,7 @@ public class SendToMethodReturnValueHandlerTests {
}
}
@SendTo
@Retention(RetentionPolicy.RUNTIME)
@interface MySendTo {
@ -590,6 +650,7 @@ public class SendToMethodReturnValueHandlerTests {
String[] dest();
}
@SendToUser
@Retention(RetentionPolicy.RUNTIME)
@interface MySendToUser {
@ -599,56 +660,6 @@ public class SendToMethodReturnValueHandlerTests {
}
@SuppressWarnings("unused")
String handleNoAnnotations() {
return PAYLOAD;
}
@SendTo @SuppressWarnings("unused")
String handleAndSendToDefaultDestination() {
return PAYLOAD;
}
@SendTo({"/dest1", "/dest2"}) @SuppressWarnings("unused")
String handleAndSendTo() {
return PAYLOAD;
}
@SendTo("/topic/chat.message.filtered.{roomName}") @SuppressWarnings("unused")
String handleAndSendToWithPlaceholders() {
return PAYLOAD;
}
@SendToUser @SuppressWarnings("unused")
String handleAndSendToUserDefaultDestination() {
return PAYLOAD;
}
@SendToUser(broadcast = false) @SuppressWarnings("unused")
String handleAndSendToUserDefaultDestinationSingleSession() {
return PAYLOAD;
}
@SendToUser({"/dest1", "/dest2"}) @SuppressWarnings("unused")
String handleAndSendToUser() {
return PAYLOAD;
}
@SendToUser(destinations = { "/dest1", "/dest2" }, broadcast = false) @SuppressWarnings("unused")
String handleAndSendToUserSingleSession() {
return PAYLOAD;
}
@JsonView(MyJacksonView1.class) @SuppressWarnings("unused")
JacksonViewBean handleAndSendToJsonView() {
JacksonViewBean payload = new JacksonViewBean();
payload.setWithView1("with");
payload.setWithView2("with");
payload.setWithoutView("without");
return payload;
}
@MySendTo(dest = "/dest-default") @SuppressWarnings("unused")
private static class SendToTestBean {
@ -667,6 +678,7 @@ public class SendToMethodReturnValueHandlerTests {
}
}
@MySendToUser(dest = "/dest-default") @SuppressWarnings("unused")
private static class SendToUserTestBean {
@ -685,6 +697,7 @@ public class SendToMethodReturnValueHandlerTests {
}
}
@MySendToUser(dest = "/dest-default") @SuppressWarnings("unused")
private static class SendToUserWithSendToOverrideTestBean {
@ -701,8 +714,10 @@ public class SendToMethodReturnValueHandlerTests {
private interface MyJacksonView1 {}
private interface MyJacksonView2 {}
@SuppressWarnings("unused")
private static class JacksonViewBean {

View File

@ -16,11 +16,9 @@
package org.springframework.test.util;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import com.jayway.jsonpath.InvalidPathException;
import com.jayway.jsonpath.JsonPath;
import org.hamcrest.Matcher;
@ -28,11 +26,9 @@ import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.springframework.test.util.AssertionErrors.assertEquals;
import static org.springframework.test.util.AssertionErrors.assertTrue;
import static org.springframework.test.util.AssertionErrors.fail;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.core.IsInstanceOf.*;
import static org.springframework.test.util.AssertionErrors.*;
/**
* A helper class for applying assertions via JSON path expressions.
@ -73,7 +69,7 @@ public class JsonPathExpectationsHelper {
* @param matcher the matcher with which to assert the result
*/
@SuppressWarnings("unchecked")
public <T> void assertValue(String content, Matcher<T> matcher) throws ParseException {
public <T> void assertValue(String content, Matcher<T> matcher) {
T value = (T) evaluateJsonPath(content);
assertThat("JSON path \"" + this.expression + "\"", value, matcher);
}
@ -85,10 +81,10 @@ public class JsonPathExpectationsHelper {
* @param content the JSON content
* @param matcher the matcher with which to assert the result
* @param targetType a the expected type of the resulting value
* @since 5.0
* @since 4.3.3
*/
@SuppressWarnings("unchecked")
public <T> void assertValue(String content, Matcher<T> matcher, Class<T> targetType) throws ParseException {
public <T> void assertValue(String content, Matcher<T> matcher, Class<T> targetType) {
T value = (T) evaluateJsonPath(content, targetType);
assertThat("JSON path \"" + this.expression + "\"", value, matcher);
}
@ -99,7 +95,7 @@ public class JsonPathExpectationsHelper {
* @param content the JSON content
* @param expectedValue the expected value
*/
public void assertValue(String content, Object expectedValue) throws ParseException {
public void assertValue(String content, Object expectedValue) {
Object actualValue = evaluateJsonPath(content);
if ((actualValue instanceof List) && !(expectedValue instanceof List)) {
@SuppressWarnings("rawtypes")
@ -126,7 +122,7 @@ public class JsonPathExpectationsHelper {
* @param content the JSON content
* @since 4.2.1
*/
public void assertValueIsString(String content) throws ParseException {
public void assertValueIsString(String content) {
Object value = assertExistsAndReturn(content);
assertThat(failureReason("a string", value), value, instanceOf(String.class));
}
@ -137,7 +133,7 @@ public class JsonPathExpectationsHelper {
* @param content the JSON content
* @since 4.2.1
*/
public void assertValueIsBoolean(String content) throws ParseException {
public void assertValueIsBoolean(String content) {
Object value = assertExistsAndReturn(content);
assertThat(failureReason("a boolean", value), value, instanceOf(Boolean.class));
}
@ -148,7 +144,7 @@ public class JsonPathExpectationsHelper {
* @param content the JSON content
* @since 4.2.1
*/
public void assertValueIsNumber(String content) throws ParseException {
public void assertValueIsNumber(String content) {
Object value = assertExistsAndReturn(content);
assertThat(failureReason("a number", value), value, instanceOf(Number.class));
}
@ -158,7 +154,7 @@ public class JsonPathExpectationsHelper {
* and assert that the resulting value is an array.
* @param content the JSON content
*/
public void assertValueIsArray(String content) throws ParseException {
public void assertValueIsArray(String content) {
Object value = assertExistsAndReturn(content);
assertThat(failureReason("an array", value), value, instanceOf(List.class));
}
@ -169,7 +165,7 @@ public class JsonPathExpectationsHelper {
* @param content the JSON content
* @since 4.2.1
*/
public void assertValueIsMap(String content) throws ParseException {
public void assertValueIsMap(String content) {
Object value = assertExistsAndReturn(content);
assertThat(failureReason("a map", value), value, instanceOf(Map.class));
}
@ -182,7 +178,7 @@ public class JsonPathExpectationsHelper {
* that the value at the given path is not <em>empty</em>.
* @param content the JSON content
*/
public void exists(String content) throws ParseException {
public void exists(String content) {
assertExistsAndReturn(content);
}
@ -194,7 +190,7 @@ public class JsonPathExpectationsHelper {
* that the value at the given path is <em>empty</em>.
* @param content the JSON content
*/
public void doesNotExist(String content) throws ParseException {
public void doesNotExist(String content) {
Object value;
try {
value = evaluateJsonPath(content);
@ -207,7 +203,7 @@ public class JsonPathExpectationsHelper {
assertTrue(reason, ((List<?>) value).isEmpty());
}
else {
assertTrue(reason, value == null);
assertTrue(reason, (value == null));
}
}
@ -218,7 +214,7 @@ public class JsonPathExpectationsHelper {
* {@link ObjectUtils#isEmpty(Object)}.
* @param content the JSON content
*/
public void assertValueIsEmpty(String content) throws ParseException {
public void assertValueIsEmpty(String content) {
Object value = evaluateJsonPath(content);
assertTrue(failureReason("an empty value", value), ObjectUtils.isEmpty(value));
}
@ -230,37 +226,37 @@ public class JsonPathExpectationsHelper {
* {@link ObjectUtils#isEmpty(Object)}.
* @param content the JSON content
*/
public void assertValueIsNotEmpty(String content) throws ParseException {
public void assertValueIsNotEmpty(String content) {
Object value = evaluateJsonPath(content);
assertTrue(failureReason("a non-empty value", value), !ObjectUtils.isEmpty(value));
}
private String failureReason(String expectedDescription, Object value) {
return String.format("Expected %s at JSON path \"%s\" but found: %s", expectedDescription, this.expression,
ObjectUtils.nullSafeToString(StringUtils.quoteIfString(value)));
ObjectUtils.nullSafeToString(StringUtils.quoteIfString(value)));
}
private Object evaluateJsonPath(String content) throws ParseException {
private Object evaluateJsonPath(String content) {
String message = "No value at JSON path \"" + this.expression + "\", exception: ";
try {
return this.jsonPath.read(content);
}
catch (InvalidPathException | IndexOutOfBoundsException ex) {
catch (Throwable ex) {
throw new AssertionError(message + ex.getMessage());
}
}
private Object evaluateJsonPath(String content, Class<?> targetType) throws ParseException {
private Object evaluateJsonPath(String content, Class<?> targetType) {
String message = "No value at JSON path \"" + this.expression + "\", exception: ";
try {
return JsonPath.parse(content).read(this.expression, targetType);
}
catch (InvalidPathException | IndexOutOfBoundsException ex) {
catch (Throwable ex) {
throw new AssertionError(message + ex.getMessage());
}
}
private Object assertExistsAndReturn(String content) throws ParseException {
private Object assertExistsAndReturn(String content) {
Object value = evaluateJsonPath(content);
String reason = "No value at JSON path \"" + this.expression + "\"";
assertTrue(reason, value != null);

View File

@ -74,6 +74,7 @@ public class JsonPathRequestMatchers {
* accepts a target type for the resulting value that the matcher can work
* reliably against. This can be useful for matching numbers reliably for
* example coercing an integer into a double.
* @since 4.3.3
*/
public <T> RequestMatcher value(final Matcher<T> matcher, final Class<T> targetType) {
return new AbstractJsonPathRequestMatcher() {

View File

@ -20,7 +20,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.Is.*;
/**
* Unit tests for {@link JsonPathExpectationsHelper}.

View File

@ -70,7 +70,7 @@ public class AsyncTests {
this.mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
}
@ -98,7 +98,7 @@ public class AsyncTests {
.andExpect(request().asyncStarted())
.andDo(MvcResult::getAsyncResult)
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.5}"));
}
@ -112,7 +112,7 @@ public class AsyncTests {
this.mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
}
@ -125,11 +125,11 @@ public class AsyncTests {
this.mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
}
@Test // SPR-13079
@Test // SPR-13079
public void deferredResultWithDelayedError() throws Exception {
MvcResult mvcResult = this.mockMvc.perform(get("/1").param("deferredResultWithDelayedError", "true"))
.andExpect(request().asyncStarted())
@ -150,7 +150,7 @@ public class AsyncTests {
this.mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
}
@ -162,7 +162,7 @@ public class AsyncTests {
this.mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
}
@ -183,7 +183,7 @@ public class AsyncTests {
this.mockMvc.perform(asyncDispatch(mvcResult))
.andDo(print(writer))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
assertTrue(writer.toString().contains("Async started = false"));

View File

@ -630,7 +630,6 @@ public class AsyncRestTemplateIntegrationTests extends AbstractJettyServerTestCa
AsyncClientHttpRequestExecution execution) throws IOException {
request = new HttpRequestWrapper(request) {
@Override
public URI getURI() {
try {

View File

@ -240,9 +240,7 @@ public class RestTemplateIntegrationTests extends AbstractJettyServerTestCase {
assertFalse(s.contains("\"without\":\"without\""));
}
// SPR-12123
@Test
@Test // SPR-12123
public void serverPort() {
String s = template.getForObject("http://localhost:{port}/get", String.class, port);
assertEquals("Invalid content", helloWorld, s);

View File

@ -86,9 +86,7 @@ public class RequestPartServletServerHttpRequestTests {
assertArrayEquals(bytes, result);
}
// SPR-13317
@Test
@Test // SPR-13317
public void getBodyWithWrappedRequest() throws Exception {
byte[] bytes = "content".getBytes("UTF-8");
MultipartFile part = new MockMultipartFile("part", "", "application/json", bytes);
@ -100,12 +98,9 @@ public class RequestPartServletServerHttpRequestTests {
assertArrayEquals(bytes, result);
}
// SPR-13096
@Test
@Test // SPR-13096
public void getBodyViaRequestParameter() throws Exception {
MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest() {
@Override
public HttpHeaders getMultipartHeaders(String paramOrFileName) {
HttpHeaders headers = new HttpHeaders();
@ -116,7 +111,6 @@ public class RequestPartServletServerHttpRequestTests {
byte[] bytes = {(byte) 0xC4};
mockRequest.setParameter("part", new String(bytes, StandardCharsets.ISO_8859_1));
ServerHttpRequest request = new RequestPartServletServerHttpRequest(mockRequest, "part");
byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
assertArrayEquals(bytes, result);
}
@ -124,7 +118,6 @@ public class RequestPartServletServerHttpRequestTests {
@Test
public void getBodyViaRequestParameterWithRequestEncoding() throws Exception {
MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest() {
@Override
public HttpHeaders getMultipartHeaders(String paramOrFileName) {
HttpHeaders headers = new HttpHeaders();
@ -136,7 +129,6 @@ public class RequestPartServletServerHttpRequestTests {
mockRequest.setParameter("part", new String(bytes, StandardCharsets.ISO_8859_1));
mockRequest.setCharacterEncoding("iso-8859-1");
ServerHttpRequest request = new RequestPartServletServerHttpRequest(mockRequest, "part");
byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
assertArrayEquals(bytes, result);
}

View File

@ -67,16 +67,16 @@ public class ScriptTemplateViewTests {
this.view = new ScriptTemplateView();
}
@Test
public void missingScriptTemplateConfig() throws Exception {
try {
this.view.setApplicationContext(new StaticApplicationContext());
fail("Should have thrown ApplicationContextException");
}
catch (ApplicationContextException ex) {
assertTrue(ex.getMessage().contains("ScriptTemplateConfig"));
return;
}
fail();
}
@Test
@ -158,7 +158,6 @@ public class ScriptTemplateViewTests {
}
catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(), containsString("instance"));
return;
}
}
@ -199,9 +198,7 @@ public class ScriptTemplateViewTests {
}
catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(), containsString("sharedEngine"));
return;
}
fail();
}
@Test // SPR-14210