Allow to customize TestDispatcherServlet

This commit introduces the `DispatcherServletCustomizer` callback
interface that can be used to customize the `DispatcherServlet` that a
`MockMvc` is using.

Previously, only the `dispatchOptions` flag can be customized. This
commit allows to customize any property of `DispatcherServlet` before it
is initialized.

Issue: SPR-14277
This commit is contained in:
Stephane Nicoll
2016-10-28 14:31:44 +02:00
parent c036e4019f
commit 30291a8cd7
4 changed files with 88 additions and 7 deletions

View File

@@ -20,11 +20,14 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.DispatcherServlet;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
@@ -36,6 +39,7 @@ import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
* @author Rob Winch
* @author Sebastien Deleuze
* @author Sam Brannen
* @author Stephane Nicoll
*/
public class DefaultMockMvcBuilderTests {
@@ -124,4 +128,32 @@ public class DefaultMockMvcBuilderTests {
assertSame(root, WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
/**
* See /SPR-14277
*/
@Test
public void dispatcherServletCustomizer() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(root);
builder.addDispatcherServletCustomizer(ds -> ds.setContextId("test-id"));
builder.dispatchOptions(true);
MockMvc mvc = builder.build();
DispatcherServlet ds = (DispatcherServlet) new DirectFieldAccessor(mvc)
.getPropertyValue("servlet");
assertEquals("test-id", ds.getContextId());
}
@Test
public void dispatcherServletCustomizerProcessedInOrder() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(root);
builder.addDispatcherServletCustomizer(ds -> ds.setContextId("test-id"));
builder.addDispatcherServletCustomizer(ds -> ds.setContextId("override-id"));
builder.dispatchOptions(true);
MockMvc mvc = builder.build();
DispatcherServlet ds = (DispatcherServlet) new DirectFieldAccessor(mvc)
.getPropertyValue("servlet");
assertEquals("override-id", ds.getContextId());
}
}