Skip to content

Commit d15abd5

Browse files
blake-baumanrstoyanchev
authored andcommitted
Add option to set Principal in MockServerWebExchange
See gh-34789 Signed-off-by: blake_bauman <[email protected]>
1 parent 44500cf commit d15abd5

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

spring-test/src/main/java/org/springframework/mock/web/server/MockServerWebExchange.java

+20-2
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
package org.springframework.mock.web.server;
1818

19+
import java.security.Principal;
20+
1921
import reactor.core.publisher.Mono;
2022

2123
import org.springframework.context.ApplicationContext;
@@ -39,16 +41,19 @@
3941
* @since 5.0
4042
*/
4143
public final class MockServerWebExchange extends DefaultServerWebExchange {
44+
private final Mono<Principal> principalMono;
4245

4346

4447
private MockServerWebExchange(
4548
MockServerHttpRequest request, @Nullable WebSessionManager sessionManager,
46-
@Nullable ApplicationContext applicationContext) {
49+
@Nullable ApplicationContext applicationContext, Mono<Principal> principalMono) {
4750

4851
super(request, new MockServerHttpResponse(),
4952
sessionManager != null ? sessionManager : new DefaultWebSessionManager(),
5053
ServerCodecConfigurer.create(), new AcceptHeaderLocaleContextResolver(),
5154
applicationContext);
55+
56+
this.principalMono = principalMono;
5257
}
5358

5459

@@ -57,6 +62,12 @@ public MockServerHttpResponse getResponse() {
5762
return (MockServerHttpResponse) super.getResponse();
5863
}
5964

65+
@SuppressWarnings("unchecked")
66+
@Override
67+
public <T extends Principal> Mono<T> getPrincipal() {
68+
return (Mono<T>)this.principalMono;
69+
}
70+
6071

6172
/**
6273
* Create a {@link MockServerWebExchange} from the given mock request.
@@ -111,6 +122,8 @@ public static class Builder {
111122
@Nullable
112123
private ApplicationContext applicationContext;
113124

125+
private Mono<Principal> principalMono = Mono.empty();
126+
114127
public Builder(MockServerHttpRequest request) {
115128
this.request = request;
116129
}
@@ -147,11 +160,16 @@ public Builder applicationContext(ApplicationContext applicationContext) {
147160
return this;
148161
}
149162

163+
public Builder principal(@Nullable Principal principal) {
164+
this.principalMono = (principal == null) ? Mono.empty() : Mono.just(principal);
165+
return this;
166+
}
167+
150168
/**
151169
* Build the {@code MockServerWebExchange} instance.
152170
*/
153171
public MockServerWebExchange build() {
154-
return new MockServerWebExchange(this.request, this.sessionManager, this.applicationContext);
172+
return new MockServerWebExchange(this.request, this.sessionManager, this.applicationContext, this.principalMono);
155173
}
156174
}
157175

0 commit comments

Comments
 (0)