Browse Source

Introduce method in MockHttpServletRequestBuilder to set remote address

Co-authored-by: Sam Brannen <sam@sambrannen.com>
Closes gh-30497
pull/30502/head
greg.lee 2 years ago committed by Sam Brannen
parent
commit
e5ee369e70
  1. 20
      spring-test/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java
  2. 9
      spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java

20
spring-test/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java

@ -103,6 +103,9 @@ public class MockHttpServletRequestBuilder @@ -103,6 +103,9 @@ public class MockHttpServletRequestBuilder
@Nullable
private MockHttpSession session;
@Nullable
private String remoteAddress;
@Nullable
private String characterEncoding;
@ -526,6 +529,17 @@ public class MockHttpServletRequestBuilder @@ -526,6 +529,17 @@ public class MockHttpServletRequestBuilder
return this;
}
/**
* Set the remote address of the request.
* @param remoteAddress the remote address (IP)
* @since 6.1
*/
public MockHttpServletRequestBuilder remoteAddress(String remoteAddress) {
Assert.hasText(remoteAddress, "'remoteAddress' must not be null or blank");
this.remoteAddress = remoteAddress;
return this;
}
/**
* An extension point for further initialization of {@link MockHttpServletRequest}
* in ways not built directly into the {@code MockHttpServletRequestBuilder}.
@ -583,6 +597,9 @@ public class MockHttpServletRequestBuilder @@ -583,6 +597,9 @@ public class MockHttpServletRequestBuilder
if (this.session == null) {
this.session = parentBuilder.session;
}
if (this.remoteAddress == null) {
this.remoteAddress = parentBuilder.remoteAddress;
}
if (this.characterEncoding == null) {
this.characterEncoding = parentBuilder.characterEncoding;
@ -687,6 +704,9 @@ public class MockHttpServletRequestBuilder @@ -687,6 +704,9 @@ public class MockHttpServletRequestBuilder
if (this.principal != null) {
request.setUserPrincipal(this.principal);
}
if (this.remoteAddress != null) {
request.setRemoteAddr(this.remoteAddress);
}
if (this.session != null) {
request.setSession(this.session);
}

9
spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java

@ -559,6 +559,15 @@ class MockHttpServletRequestBuilderTests { @@ -559,6 +559,15 @@ class MockHttpServletRequestBuilderTests {
assertThat(request.getUserPrincipal()).isEqualTo(user);
}
@Test
void remoteAddress() {
String ip = "10.0.0.1";
this.builder.remoteAddress(ip);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertThat(request.getRemoteAddr()).isEqualTo(ip);
}
@Test // SPR-12945
void mergeInvokesDefaultRequestPostProcessorFirst() {
final String ATTR = "ATTR";

Loading…
Cancel
Save