ResponseEntityExceptionHandlerTests.java 8.7 KB
Newer Older
1
/*
2
 * Copyright 2002-2013 the original author or authors.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.web.servlet.mvc.method.annotation;

import static org.junit.Assert.assertEquals;
19
import static org.junit.Assert.assertSame;
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
import static org.junit.Assert.assertTrue;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
40
import org.springframework.http.server.ServletServerHttpRequest;
R
Rob Winch 已提交
41 42
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
43 44 45 46 47 48 49 50 51 52 53 54 55
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
56
import org.springframework.web.servlet.NoHandlerFoundException;
57 58 59 60
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

/**
61
 * Test fixture for {@link ResponseEntityExceptionHandler}.
62 63 64
 *
 * @author Rossen Stoyanchev
 */
65
public class ResponseEntityExceptionHandlerTests {
66

67
	private ResponseEntityExceptionHandler exceptionHandlerSupport;
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

	private DefaultHandlerExceptionResolver defaultExceptionResolver;

	private WebRequest request;

	private HttpServletRequest servletRequest;

	private MockHttpServletResponse servletResponse;


	@Before
	public void setup() {
		this.servletRequest = new MockHttpServletRequest();
		this.servletResponse = new MockHttpServletResponse();
		this.request = new ServletWebRequest(this.servletRequest, this.servletResponse);

		this.exceptionHandlerSupport = new ApplicationExceptionHandler();
		this.defaultExceptionResolver = new DefaultHandlerExceptionResolver();
	}

	@Test
	public void supportsAllDefaultHandlerExceptionResolverExceptionTypes() throws Exception {

91
		Method annotMethod = ResponseEntityExceptionHandler.class.getMethod("handleException", Exception.class, WebRequest.class);
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
		ExceptionHandler annot = annotMethod.getAnnotation(ExceptionHandler.class);
		List<Class<? extends Throwable>> supportedTypes = Arrays.asList(annot.value());

		for (Method method : DefaultHandlerExceptionResolver.class.getDeclaredMethods()) {
			Class<?>[] paramTypes = method.getParameterTypes();
			if (method.getName().startsWith("handle") && (paramTypes.length == 4)) {
				String name = paramTypes[0].getSimpleName();
				assertTrue("@ExceptionHandler is missing " + name, supportedTypes.contains(paramTypes[0]));
			}
		}
	}

	@Test
	public void noSuchRequestHandlingMethod() {
		Exception ex = new NoSuchRequestHandlingMethodException("GET", TestController.class);
		testException(ex);
	}

	@Test
	public void httpRequestMethodNotSupported() {
		List<String> supported = Arrays.asList("POST", "DELETE");
		Exception ex = new HttpRequestMethodNotSupportedException("GET", supported);

		ResponseEntity<Object> responseEntity = testException(ex);
		assertEquals(EnumSet.of(HttpMethod.POST, HttpMethod.DELETE), responseEntity.getHeaders().getAllow());

	}

	@Test
	public void handleHttpMediaTypeNotSupported() {
		List<MediaType> acceptable = Arrays.asList(MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML);
		Exception ex = new HttpMediaTypeNotSupportedException(MediaType.APPLICATION_JSON, acceptable);

		ResponseEntity<Object> responseEntity = testException(ex);
		assertEquals(acceptable, responseEntity.getHeaders().getAccept());
	}

	@Test
	public void httpMediaTypeNotAcceptable() {
		Exception ex = new HttpMediaTypeNotAcceptableException("");
		testException(ex);
	}

	@Test
	public void missingServletRequestParameter() {
		Exception ex = new MissingServletRequestParameterException("param", "type");
		testException(ex);
	}

	@Test
	public void servletRequestBindingException() {
		Exception ex = new ServletRequestBindingException("message");
		testException(ex);
	}

	@Test
	public void conversionNotSupported() {
		Exception ex = new ConversionNotSupportedException(new Object(), Object.class, null);
		testException(ex);
	}

	@Test
	public void typeMismatch() {
		Exception ex = new TypeMismatchException("foo", String.class);
		testException(ex);
	}

	@Test
	public void httpMessageNotReadable() {
		Exception ex = new HttpMessageNotReadableException("message");
		testException(ex);
	}

	@Test
	public void httpMessageNotWritable() {
		Exception ex = new HttpMessageNotWritableException("");
		testException(ex);
	}

	@Test
	public void methodArgumentNotValid() {
		Exception ex = new MethodArgumentNotValidException(null, null);
		testException(ex);
	}

	@Test
	public void missingServletRequestPart() {
		Exception ex = new MissingServletRequestPartException("partName");
		testException(ex);
	}

	@Test
	public void bindException() {
		Exception ex = new BindException(new Object(), "name");
		testException(ex);
	}

189 190 191 192 193 194 195 196 197
	@Test
	public void noHandlerFoundException() {
		ServletServerHttpRequest req = new ServletServerHttpRequest(
				new MockHttpServletRequest("GET","/resource"));
		Exception ex = new NoHandlerFoundException(req.getMethod().toString(),
				req.getServletRequest().getRequestURI(),req.getHeaders());
		testException(ex);
	}

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
	@Test
	public void controllerAdvice() throws Exception {
		StaticWebApplicationContext cxt = new StaticWebApplicationContext();
		cxt.registerSingleton("exceptionHandler", ApplicationExceptionHandler.class);
		cxt.refresh();

		ExceptionHandlerExceptionResolver resolver = new ExceptionHandlerExceptionResolver();
		resolver.setApplicationContext(cxt);
		resolver.afterPropertiesSet();

		ServletRequestBindingException ex = new ServletRequestBindingException("message");
		resolver.resolveException(this.servletRequest, this.servletResponse, null, ex);

		assertEquals(400, this.servletResponse.getStatus());
		assertEquals("error content", this.servletResponse.getContentAsString());
		assertEquals("someHeaderValue", this.servletResponse.getHeader("someHeader"));
	}


	private ResponseEntity<Object> testException(Exception ex) {
		ResponseEntity<Object> responseEntity = this.exceptionHandlerSupport.handleException(ex, this.request);
219 220 221 222 223 224

		// SPR-9653
		if (HttpStatus.INTERNAL_SERVER_ERROR.equals(responseEntity.getStatusCode())) {
			assertSame(ex, this.servletRequest.getAttribute("javax.servlet.error.exception"));
		}

225 226 227 228 229 230 231 232 233 234 235 236
		this.defaultExceptionResolver.resolveException(this.servletRequest, this.servletResponse, null, ex);

		assertEquals(this.servletResponse.getStatus(), responseEntity.getStatusCode().value());

		return responseEntity;
	}


	private static class TestController {
	}

	@ControllerAdvice
237
	private static class ApplicationExceptionHandler extends ResponseEntityExceptionHandler {
238 239

		@Override
240
		protected ResponseEntity<Object> handleServletRequestBindingException(ServletRequestBindingException ex,
241 242 243
				HttpHeaders headers, HttpStatus status, WebRequest request) {

			headers.set("someHeader", "someHeaderValue");
244
			return handleExceptionInternal(ex, "error content", headers, status, request);
245 246 247 248 249 250
		}


	}

}