javaspring-bootunit-testingannotationsaspect

How do I test private annotation aspect in spring boot?


How do I test private annotation aspect in spring boot ?

Example:

@Aspect
@Component
@Slf4j
public class AspectClass {
    @AfterReturning(value = "@annotation(CustomAnnotation)")
    private void privateMethod(JoinPoint joinPoint) 
    {
       // Test this part
       System.out.println("Want to test this");
    }
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface  CustomAnnotation {
    String methodName() default "";
}

Expect to test the private method in Aspect with annotation trigger


Solution

  • If your application is spring-boot-web then you can use your existing Application.java or you have to ceate a new ApplicationTest.java that atleast have the following

    @Configuration
    @SpringBootApplication
    public class ApplicationTest {}
    

    Sample Test:

    // AnnotationExecutor.java
    @Component
    public class AnnotationExecutor {
    
        @CustomAnnotation(methodName = "CustomAnnotation")
        public void someMethod(...) {
           // code
           ...
        }
    
    }
    
    // AnnotationTest.java
    @ExtendWith(SpringExtension.class)
    @SpringBootTest(classes = ApplicationTest.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    @ActiveProfiles("test")
    @ComponentScan("com.your.package.path.*")
    public class AnnotationTest {
    
        @Autowired
        private AnnotationExecutor annotationExecutor;
    
        @Test
        public void sampleTest(){
            annotationExecutor.someMethod(...);
            System.out.println("Test completed");
            // continue for assertion and testing ...
        }
    }
    

    Expected output:

    Want to test this
    Test completed
    \\ ...