I use Springboot and I want test my new custom annotation by JUnit.
My original code with my @CronLogger
custom annotation on importData
method:
@Service
@RequiredArgsConstructor
@Slf4j
public class ImportTask {
@Async
@Scheduled(cron = "${import}")
@SchedulerLock(name = "import")
@CronLogger()
public void importData() {
...
}
}
My custom annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CronLogger {
}
My custom Aspect method:
@Aspect
@Component
@EnableAspectJAutoProxy
public class CronLoggerAspect {
private static final Logger log = LoggerFactory.getLogger(CronLoggerAspect.class);
@Around("@annotation(CronLogger)")
public Object trace(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("CronLogger");
log.debug("CronLogger");
return joinPoint.proceed();
}
}
My JUnit test:
@Slf4j
@ExtendWith(MockitoExtension.class)
@Import(AnnotationAwareAspectJAutoProxyCreator.class) // activate aspect
class ImportTaskTest {
@InjectMocks
private ImportTask importTask;
@Test
void importData() throws JSchException, SftpException, SftpTransfertException {
// execute test
importTask.importData();
}
}
the result is OK but whitout execute Aspect method code.
@ExtendWith(SpringExtension.class)
@SpringBootTest
@ActiveProfiles("sit")
class TaskTest {
@Autowired
private TaskService taskService;
@Test
void testCronLoggerSuccess() throws CronException {
taskService.testCronLogger("test Success");
...
}
}
Nota: @ActiveProfiles("sit")
use for H2 database.