Untitled

 avatar
unknown
java
2 years ago
2.7 kB
4
Indexable
package com.codility.external;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringAOPApplicationTests {

    @Test
    void is_always_logging_after_removeAllNumbers() {
        StringManipulationService manipulationService = new StringManipulationService();
        manipulationService.removeAllNumbers("12345");

        Logger log = LoggerFactory.getLogger(StringManipulationAspect.class);
        int logCount = TestLogger.getLogCount(log);
        Assertions.assertEquals(2, logCount);
    }
}

@Aspect
class StringManipulationAspect {
    public static final Logger log = LoggerFactory.getLogger(StringManipulationAspect.class);

    @Before("execution(* com.codility.external.StringManipulationService.*(..))")
    public void logMethodExecutionStart() {
        log.info("Method execution started");
    }

    @AfterReturning("execution(* com.codility.external.StringManipulationService.capitalizeAllLetters(..))")
    public void logMethodFinishedSuccessfully() {
        log.info("Finished successfully");
    }

    @Around("execution(* com.codility.external.StringManipulationService.removeAllWhitespaces(..))")
    public Object logMethodExecutionDuration(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long executionTime = System.currentTimeMillis() - startTime;
        log.info("Duration in milliseconds: {}", executionTime);
        return result;
    }

    @AfterReturning("execution(* com.codility.external.StringManipulationService.removeAllNumbers(..))")
    public void logMethodRemovedAllNumbers() {
        log.info("Removed all numbers");
    }

    @AfterThrowing(pointcut = "execution(* com.codility.external.StringManipulationService.removeAllNumbers(..))",
            throwing = "exception")
    public void logMethodException(IllegalStateException exception) {
        log.error("Error state", exception);
    }
}

class TestLogger {
    private static int logCount = 0;

    public static void log() {
        logCount++;
    }

    public static int getLogCount(Logger log) {
        return logCount;
    }
}

class StringManipulationService {
    public String removeAllNumbers(String target) {
        if (target == null) {
            throw new IllegalStateException("String must not be null");
        }
        String result = target.replaceAll("\\d", "");
        TestLogger.log();
        return result;
    }
}
Editor is loading...