Skip to content

Commit b478e5b

Browse files
MariuszCwiklarwinch
authored andcommitted
gh-6899: @WithMockUser as metaannotation
1 parent 86fbb8d commit b478e5b

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

test/src/main/java/org/springframework/security/test/context/support/WithSecurityContextTestExecutionListener.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ private TestSecurityContext createTestSecurityContext(AnnotatedElement annotated
148148
}
149149

150150
private Annotation findAnnotation(AnnotatedElement annotated, Class<? extends Annotation> type) {
151-
Annotation findAnnotation = AnnotationUtils.findAnnotation(annotated, type);
151+
Annotation findAnnotation = AnnotatedElementUtils.findMergedAnnotation(annotated, type);
152152
if (findAnnotation != null) {
153153
return findAnnotation;
154154
}

test/src/test/java/org/springframework/security/test/context/showcase/WithMockUserTests.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,18 @@
1616

1717
package org.springframework.security.test.context.showcase;
1818

19+
import java.lang.annotation.ElementType;
20+
import java.lang.annotation.Inherited;
21+
import java.lang.annotation.Retention;
22+
import java.lang.annotation.RetentionPolicy;
23+
import java.lang.annotation.Target;
24+
1925
import org.junit.jupiter.api.Test;
2026
import org.junit.jupiter.api.extension.ExtendWith;
2127

2228
import org.springframework.beans.factory.annotation.Autowired;
2329
import org.springframework.context.annotation.ComponentScan;
30+
import org.springframework.core.annotation.AliasFor;
2431
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
2532
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
2633
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
@@ -77,6 +84,24 @@ public void getMessageWithMockUserCustomAuthorities() {
7784
assertThat(message).contains("admin").contains("ADMIN").contains("USER").doesNotContain("ROLE_");
7885
}
7986

87+
@Retention(RetentionPolicy.RUNTIME)
88+
@Target(ElementType.METHOD)
89+
@Inherited
90+
@WithMockUser(roles = "ADMIN")
91+
public @interface WithAdminUser {
92+
93+
@AliasFor(annotation = WithMockUser.class, attribute = "value")
94+
String value();
95+
96+
}
97+
98+
@Test
99+
@WithAdminUser("admin")
100+
public void getMessageWithMetaAnnotationAdminUser() {
101+
String message = this.messageService.getMessage();
102+
assertThat(message).contains("admin").contains("ADMIN").contains("ROLE_ADMIN");
103+
}
104+
80105
@EnableGlobalMethodSecurity(prePostEnabled = true)
81106
@ComponentScan(basePackageClasses = HelloMessageService.class)
82107
static class Config {

0 commit comments

Comments
 (0)