Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
\\ ...

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading