Turn registered controller classes into controller instances on the fly

Issue: SPR-16520
This commit is contained in:
Juergen Hoeller 2018-02-25 14:29:44 +01:00
parent 85984f3b72
commit 01d9475bcc
8 changed files with 72 additions and 76 deletions

View File

@ -17,10 +17,10 @@
package org.springframework.test.web.reactive.server; package org.springframework.test.web.reactive.server;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.format.FormatterRegistry; import org.springframework.format.FormatterRegistry;
@ -56,21 +56,24 @@ class DefaultControllerSpec extends AbstractMockServerSpec<WebTestClient.Control
DefaultControllerSpec(Object... controllers) { DefaultControllerSpec(Object... controllers) {
Assert.isTrue(!ObjectUtils.isEmpty(controllers), "At least one controller is required"); Assert.isTrue(!ObjectUtils.isEmpty(controllers), "At least one controller is required");
Assert.isTrue(checkInstances(controllers), "Controller instances are required"); this.controllers = instantiateIfNecessary(controllers);
this.controllers = Arrays.asList(controllers);
} }
private static List<Object> instantiateIfNecessary(Object[] specified) {
List<Object> instances = new ArrayList<>(specified.length);
for (Object obj : specified) {
instances.add(obj instanceof Class ? BeanUtils.instantiateClass((Class<?>) obj) : obj);
}
return instances;
}
@Override @Override
public DefaultControllerSpec controllerAdvice(Object... controllerAdvice) { public DefaultControllerSpec controllerAdvice(Object... controllerAdvices) {
Assert.isTrue(checkInstances(controllerAdvice), "ControllerAdvice instances are required"); this.controllerAdvice.addAll(instantiateIfNecessary(controllerAdvices));
this.controllerAdvice.addAll(Arrays.asList(controllerAdvice));
return this; return this;
} }
private boolean checkInstances(Object[] objects) {
return Arrays.stream(objects).noneMatch(Class.class::isInstance);
}
@Override @Override
public DefaultControllerSpec contentTypeResolver(Consumer<RequestedContentTypeResolverBuilder> consumer) { public DefaultControllerSpec contentTypeResolver(Consumer<RequestedContentTypeResolverBuilder> consumer) {
this.configurer.contentTypeResolverConsumer = consumer; this.configurer.contentTypeResolverConsumer = consumer;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -168,6 +168,7 @@ public interface WebTestClient {
* WebFlux application will be tested without an HTTP server using a mock * WebFlux application will be tested without an HTTP server using a mock
* request and response. * request and response.
* @param controllers one or more controller instances to tests * @param controllers one or more controller instances to tests
* (specified {@code Class} will be turned into instance)
* @return chained API to customize server and client config; use * @return chained API to customize server and client config; use
* {@link MockServerSpec#configureClient()} to transition to client config * {@link MockServerSpec#configureClient()} to transition to client config
*/ */
@ -290,9 +291,8 @@ public interface WebTestClient {
interface ControllerSpec extends MockServerSpec<ControllerSpec> { interface ControllerSpec extends MockServerSpec<ControllerSpec> {
/** /**
* Register one or more * Register one or more {@link org.springframework.web.bind.annotation.ControllerAdvice}
* {@link org.springframework.web.bind.annotation.ControllerAdvice * instances to be used in tests (specified {@code Class} will be turned into instance).
* ControllerAdvice} instances to be used in tests.
*/ */
ControllerSpec controllerAdvice(Object... controllerAdvice); ControllerSpec controllerAdvice(Object... controllerAdvice);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -51,25 +51,22 @@ public class MockMvcBuilders {
* Build a {@link MockMvc} instance by registering one or more * Build a {@link MockMvc} instance by registering one or more
* {@code @Controller} instances and configuring Spring MVC infrastructure * {@code @Controller} instances and configuring Spring MVC infrastructure
* programmatically. * programmatically.
*
* <p>This allows full control over the instantiation and initialization of * <p>This allows full control over the instantiation and initialization of
* controllers and their dependencies, similar to plain unit tests while * controllers and their dependencies, similar to plain unit tests while
* also making it possible to test one controller at a time. * also making it possible to test one controller at a time.
*
* <p>When this builder is used, the minimum infrastructure required by the * <p>When this builder is used, the minimum infrastructure required by the
* {@link org.springframework.web.servlet.DispatcherServlet DispatcherServlet} * {@link org.springframework.web.servlet.DispatcherServlet DispatcherServlet}
* to serve requests with annotated controllers is created automatically * to serve requests with annotated controllers is created automatically
* and can be customized, resulting in configuration that is equivalent to * and can be customized, resulting in configuration that is equivalent to
* what MVC Java configuration provides except using builder-style methods. * what MVC Java configuration provides except using builder-style methods.
*
* <p>If the Spring MVC configuration of an application is relatively * <p>If the Spring MVC configuration of an application is relatively
* straight-forward &mdash; for example, when using the MVC namespace in * straight-forward &mdash; for example, when using the MVC namespace in
* XML or MVC Java config &mdash; then using this builder might be a good * XML or MVC Java config &mdash; then using this builder might be a good
* option for testing a majority of controllers. In such cases, a much * option for testing a majority of controllers. In such cases, a much
* smaller number of tests can be used to focus on testing and verifying * smaller number of tests can be used to focus on testing and verifying
* the actual Spring MVC configuration. * the actual Spring MVC configuration.
*
* @param controllers one or more {@code @Controller} instances to test * @param controllers one or more {@code @Controller} instances to test
* (specified {@code Class} will be turned into instance)
*/ */
public static StandaloneMockMvcBuilder standaloneSetup(Object... controllers) { public static StandaloneMockMvcBuilder standaloneSetup(Object... controllers) {
return new StandaloneMockMvcBuilder(controllers); return new StandaloneMockMvcBuilder(controllers);

View File

@ -26,6 +26,7 @@ import java.util.Map;
import java.util.function.Supplier; import java.util.function.Supplier;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
@ -37,7 +38,6 @@ import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.mock.web.MockServletContext; import org.springframework.mock.web.MockServletContext;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.PropertyPlaceholderHelper; import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver; import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
import org.springframework.util.StringValueResolver; import org.springframework.util.StringValueResolver;
@ -142,31 +142,31 @@ public class StandaloneMockMvcBuilder extends AbstractMockMvcBuilder<StandaloneM
* @see MockMvcBuilders#standaloneSetup(Object...) * @see MockMvcBuilders#standaloneSetup(Object...)
*/ */
protected StandaloneMockMvcBuilder(Object... controllers) { protected StandaloneMockMvcBuilder(Object... controllers) {
Assert.isTrue(!ObjectUtils.isEmpty(controllers), "At least one controller is required"); this.controllers = instantiateIfNecessary(controllers);
Assert.isTrue(checkInstances(controllers), "Controller instances are required");
this.controllers = Arrays.asList(controllers);
} }
private static List<Object> instantiateIfNecessary(Object[] specified) {
List<Object> instances = new ArrayList<>(specified.length);
for (Object obj : specified) {
instances.add(obj instanceof Class ? BeanUtils.instantiateClass((Class<?>) obj) : obj);
}
return instances;
}
/** /**
* Register one or more * Register one or more {@link org.springframework.web.bind.annotation.ControllerAdvice}
* {@link org.springframework.web.bind.annotation.ControllerAdvice * instances to be used in tests (specified {@code Class} will be turned into instance).
* ControllerAdvice} instances to be used in tests. * <p>Normally {@code @ControllerAdvice} are auto-detected as long as they're declared
* <p>Normally {@code @ControllerAdvice} are auto-detected as long as they're * as Spring beans. However since the standalone setup does not load any Spring config,
* declared as Spring beans. However since the standalone setup does not load * they need to be registered explicitly here instead much like controllers.
* any Spring configuration they need to be registered explicitly here
* instead much like controllers.
* @since 4.2 * @since 4.2
*/ */
public StandaloneMockMvcBuilder setControllerAdvice(Object... controllerAdvice) { public StandaloneMockMvcBuilder setControllerAdvice(Object... controllerAdvice) {
Assert.isTrue(checkInstances(controllerAdvice), "ControllerAdvice instances are required"); this.controllerAdvice = instantiateIfNecessary(controllerAdvice);
this.controllerAdvice = Arrays.asList(controllerAdvice);
return this; return this;
} }
private boolean checkInstances(Object[] objects) {
return Arrays.stream(objects).noneMatch(Class.class::isInstance);
}
/** /**
* Set the message converters to use in argument resolvers and in return value * Set the message converters to use in argument resolvers and in return value
* handlers, which support reading and/or writing to the body of the request * handlers, which support reading and/or writing to the body of the request
@ -405,7 +405,7 @@ public class StandaloneMockMvcBuilder extends AbstractMockMvcBuilder<StandaloneM
private List<ViewResolver> initViewResolvers(WebApplicationContext wac) { private List<ViewResolver> initViewResolvers(WebApplicationContext wac) {
this.viewResolvers = (this.viewResolvers != null ? this.viewResolvers : this.viewResolvers = (this.viewResolvers != null ? this.viewResolvers :
Collections.<ViewResolver>singletonList(new InternalResourceViewResolver())); Collections.singletonList(new InternalResourceViewResolver()));
for (Object viewResolver : this.viewResolvers) { for (Object viewResolver : this.viewResolvers) {
if (viewResolver instanceof WebApplicationObjectSupport) { if (viewResolver instanceof WebApplicationObjectSupport) {
((WebApplicationObjectSupport) viewResolver).setApplicationContext(wac); ((WebApplicationObjectSupport) viewResolver).setApplicationContext(wac);
@ -546,7 +546,7 @@ public class StandaloneMockMvcBuilder extends AbstractMockMvcBuilder<StandaloneM
@Override @Override
@Nullable @Nullable
public View resolveViewName(String viewName, Locale locale) throws Exception { public View resolveViewName(String viewName, Locale locale) {
return this.view; return this.view;
} }
} }

View File

@ -33,7 +33,7 @@ import org.springframework.web.reactive.config.PathMatchConfigurer;
import org.springframework.web.reactive.config.ViewResolverRegistry; import org.springframework.web.reactive.config.ViewResolverRegistry;
import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer; import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.*;
/** /**
* Unit tests for {@link DefaultControllerSpec}. * Unit tests for {@link DefaultControllerSpec}.
@ -63,19 +63,19 @@ public class DefaultControllerSpecTests {
.expectBody(String.class).isEqualTo("Handled exception"); .expectBody(String.class).isEqualTo("Handled exception");
} }
@Test(expected = IllegalArgumentException.class) @Test
public void controllerIsAnObjectInstance() { public void controllerAdviceWithClassArgument() {
new DefaultControllerSpec(MyController.class); new DefaultControllerSpec(MyController.class)
} .controllerAdvice(MyControllerAdvice.class)
.build()
@Test(expected = IllegalArgumentException.class) .get().uri("/exception")
public void controllerAdviceIsAnObjectInstance() { .exchange()
new DefaultControllerSpec(new MyController()).controllerAdvice(MyControllerAdvice.class); .expectStatus().isBadRequest()
.expectBody(String.class).isEqualTo("Handled exception");
} }
@Test @Test
public void configurerConsumers() { public void configurerConsumers() {
TestConsumer<ArgumentResolverConfigurer> argumentResolverConsumer = new TestConsumer<>(); TestConsumer<ArgumentResolverConfigurer> argumentResolverConsumer = new TestConsumer<>();
TestConsumer<RequestedContentTypeResolverBuilder> contenTypeResolverConsumer = new TestConsumer<>(); TestConsumer<RequestedContentTypeResolverBuilder> contenTypeResolverConsumer = new TestConsumer<>();
TestConsumer<CorsRegistry> corsRegistryConsumer = new TestConsumer<>(); TestConsumer<CorsRegistry> corsRegistryConsumer = new TestConsumer<>();
@ -104,6 +104,7 @@ public class DefaultControllerSpecTests {
} }
@RestController @RestController
private static class MyController { private static class MyController {
@ -119,6 +120,7 @@ public class DefaultControllerSpecTests {
} }
@ControllerAdvice @ControllerAdvice
private static class MyControllerAdvice { private static class MyControllerAdvice {
@ -128,11 +130,11 @@ public class DefaultControllerSpecTests {
} }
} }
private static class TestConsumer<T> implements Consumer<T> { private static class TestConsumer<T> implements Consumer<T> {
private T value; private T value;
public T getValue() { public T getValue() {
return this.value; return this.value;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -26,7 +26,6 @@ import com.gargoylesoftware.htmlunit.WebConnection;
import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse; import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.WebResponseData; import com.gargoylesoftware.htmlunit.WebResponseData;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -82,7 +81,7 @@ public class DelegatingWebConnectionTests {
@Before @Before
public void setup() throws Exception { public void setup() throws Exception {
request = new WebRequest(new URL("http://localhost/")); request = new WebRequest(new URL("http://localhost/"));
WebResponseData data = new WebResponseData("".getBytes("UTF-8"), 200, "", Collections.<NameValuePair> emptyList()); WebResponseData data = new WebResponseData("".getBytes("UTF-8"), 200, "", Collections.emptyList());
expectedResponse = new WebResponse(data, request, 100L); expectedResponse = new WebResponse(data, request, 100L);
webConnection = new DelegatingWebConnection(defaultConnection, webConnection = new DelegatingWebConnection(defaultConnection,
new DelegateWebConnection(matcher1, connection1), new DelegateWebConnection(matcher2, connection2)); new DelegateWebConnection(matcher1, connection1), new DelegateWebConnection(matcher2, connection2));
@ -132,14 +131,13 @@ public class DelegatingWebConnectionTests {
WebClient webClient = new WebClient(); WebClient webClient = new WebClient();
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(TestController.class).build(); MockMvc mockMvc = MockMvcBuilders.standaloneSetup().build();
MockMvcWebConnection mockConnection = new MockMvcWebConnection(mockMvc, webClient); MockMvcWebConnection mockConnection = new MockMvcWebConnection(mockMvc, webClient);
WebRequestMatcher cdnMatcher = new UrlRegexRequestMatcher(".*?//code.jquery.com/.*"); WebRequestMatcher cdnMatcher = new UrlRegexRequestMatcher(".*?//code.jquery.com/.*");
WebConnection httpConnection = new HttpWebConnection(webClient); WebConnection httpConnection = new HttpWebConnection(webClient);
WebConnection webConnection = new DelegatingWebConnection(mockConnection, new DelegateWebConnection(cdnMatcher, httpConnection)); webClient.setWebConnection(
new DelegatingWebConnection(mockConnection, new DelegateWebConnection(cdnMatcher, httpConnection)));
webClient.setWebConnection(webConnection);
Page page = webClient.getPage("http://code.jquery.com/jquery-1.11.0.min.js"); Page page = webClient.getPage("http://code.jquery.com/jquery-1.11.0.min.js");
assertThat(page.getWebResponse().getStatusCode(), equalTo(200)); assertThat(page.getWebResponse().getStatusCode(), equalTo(200));

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,10 +16,6 @@
package org.springframework.test.web.servlet.samples.standalone; package org.springframework.test.web.servlet.samples.standalone;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import org.junit.Test; import org.junit.Test;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
@ -29,6 +25,10 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
/** /**
* Exception handling via {@code @ExceptionHandler} method. * Exception handling via {@code @ExceptionHandler} method.
* *
@ -36,7 +36,6 @@ import org.springframework.web.bind.annotation.RequestMethod;
*/ */
public class ExceptionHandlerTests { public class ExceptionHandlerTests {
@Test @Test
public void testExceptionHandlerMethod() throws Exception { public void testExceptionHandlerMethod() throws Exception {
standaloneSetup(new PersonController()).build() standaloneSetup(new PersonController()).build()
@ -53,6 +52,14 @@ public class ExceptionHandlerTests {
.andExpect(forwardedUrl("globalErrorView")); .andExpect(forwardedUrl("globalErrorView"));
} }
@Test
public void testGlobalExceptionHandlerMethodUsingClassArgument() throws Exception {
standaloneSetup(PersonController.class).setControllerAdvice(GlobalExceptionHandler.class).build()
.perform(get("/person/Bonnie"))
.andExpect(status().isOk())
.andExpect(forwardedUrl("globalErrorView"));
}
@Controller @Controller
private static class PersonController { private static class PersonController {
@ -74,6 +81,7 @@ public class ExceptionHandlerTests {
} }
} }
@ControllerAdvice @ControllerAdvice
private static class GlobalExceptionHandler { private static class GlobalExceptionHandler {

View File

@ -43,7 +43,7 @@ import static org.junit.Assert.*;
/** /**
* Tests for {@link StandaloneMockMvcBuilder} * Tests for {@link StandaloneMockMvcBuilder}
* *
* @author Rossen * @author Rossen Stoyanchev
* @author Rob Winch * @author Rob Winch
* @author Sebastien Deleuze * @author Sebastien Deleuze
*/ */
@ -87,8 +87,7 @@ public class StandaloneMockMvcBuilderTests {
TestStandaloneMockMvcBuilder builder = new TestStandaloneMockMvcBuilder(new PlaceholderController()); TestStandaloneMockMvcBuilder builder = new TestStandaloneMockMvcBuilder(new PlaceholderController());
builder.addPlaceholderValue("sys.login.ajax", "/foo"); builder.addPlaceholderValue("sys.login.ajax", "/foo");
WebApplicationContext wac = builder.initWebAppContext(); WebApplicationContext wac = builder.initWebAppContext();
assertEquals(wac, WebApplicationContextUtils assertEquals(wac, WebApplicationContextUtils.getRequiredWebApplicationContext(wac.getServletContext()));
.getRequiredWebApplicationContext(wac.getServletContext()));
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
@ -125,17 +124,6 @@ public class StandaloneMockMvcBuilderTests {
assertNotNull(serializer); assertNotNull(serializer);
} }
@Test(expected = IllegalArgumentException.class)
public void controllerIsAnObjectInstance() {
new StandaloneMockMvcBuilder(PersonController.class);
}
@Test(expected = IllegalArgumentException.class)
public void controllerAdviceIsAnObjectInstance() {
new StandaloneMockMvcBuilder(new PersonController()).setControllerAdvice(PersonController.class);
}
@Controller @Controller
private static class PlaceholderController { private static class PlaceholderController {