#How do I use AOP in test classes?

1 messages · Page 1 of 1 (latest)

vale talon
#
@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.

raven monolithBOT
#

<@&1004656351647117403> please have a look, thanks.