Skip to content

Commit e5ee369

Browse files
leewin12sbrannen
andcommitted
Introduce method in MockHttpServletRequestBuilder to set remote address
Co-authored-by: Sam Brannen <[email protected]> Closes gh-30497
1 parent f5bc084 commit e5ee369

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@ public class MockHttpServletRequestBuilder
103103
@Nullable
104104
private MockHttpSession session;
105105

106+
@Nullable
107+
private String remoteAddress;
108+
106109
@Nullable
107110
private String characterEncoding;
108111

@@ -526,6 +529,17 @@ public MockHttpServletRequestBuilder principal(Principal principal) {
526529
return this;
527530
}
528531

532+
/**
533+
* Set the remote address of the request.
534+
* @param remoteAddress the remote address (IP)
535+
* @since 6.1
536+
*/
537+
public MockHttpServletRequestBuilder remoteAddress(String remoteAddress) {
538+
Assert.hasText(remoteAddress, "'remoteAddress' must not be null or blank");
539+
this.remoteAddress = remoteAddress;
540+
return this;
541+
}
542+
529543
/**
530544
* An extension point for further initialization of {@link MockHttpServletRequest}
531545
* in ways not built directly into the {@code MockHttpServletRequestBuilder}.
@@ -583,6 +597,9 @@ public Object merge(@Nullable Object parent) {
583597
if (this.session == null) {
584598
this.session = parentBuilder.session;
585599
}
600+
if (this.remoteAddress == null) {
601+
this.remoteAddress = parentBuilder.remoteAddress;
602+
}
586603

587604
if (this.characterEncoding == null) {
588605
this.characterEncoding = parentBuilder.characterEncoding;
@@ -687,6 +704,9 @@ public final MockHttpServletRequest buildRequest(ServletContext servletContext)
687704
if (this.principal != null) {
688705
request.setUserPrincipal(this.principal);
689706
}
707+
if (this.remoteAddress != null) {
708+
request.setRemoteAddr(this.remoteAddress);
709+
}
690710
if (this.session != null) {
691711
request.setSession(this.session);
692712
}

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,15 @@ void principal() {
559559
assertThat(request.getUserPrincipal()).isEqualTo(user);
560560
}
561561

562+
@Test
563+
void remoteAddress() {
564+
String ip = "10.0.0.1";
565+
this.builder.remoteAddress(ip);
566+
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
567+
568+
assertThat(request.getRemoteAddr()).isEqualTo(ip);
569+
}
570+
562571
@Test // SPR-12945
563572
void mergeInvokesDefaultRequestPostProcessorFirst() {
564573
final String ATTR = "ATTR";

0 commit comments

Comments
 (0)