@Aspect
@RequiredArgsConstructor
public class AuthAspect {
private final UserDetailsService userDetailsService;
@Before("execution(public * *()) && @annotation(withAuth)")
public void preExecute(WithAuth withAuth) {
UserDetails userDetails = userDetailsService.loadUserByUsername(withAuth.username());
List<Role> authorities = new ArrayList<>();
for (String authority : withAuth.authorities()) {
authorities.add(new Role(authority));
}
Authentication authToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), authorities);
SecurityContextHolder.getContext().setAuthentication(authToken);
}
@TestConfiguration
@EnableAspectJAutoProxy
public class TestConfig {
@Bean
public AuthAspect authAspect(UserDetailsService userDetailsService) {
return new AuthAspect(userDetailsService);
}
}
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface WithAuth {
String username() default "";
String password() default "";
String[] authorities() default {};
}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestConfiguration(proxyBeanMethods = true)
@Import(TestConfig.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class ControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
...
@Test
@WithAuth(username = "[email protected]", authorities = "admin")
public void createProductSuccess() throws Exception {
...
When I execute this test method, it isn't executing code in aspect, even tho intellij sees definition of aspect and allows me to navigate to it + it is in ApplicationContext.