mirror of
https://github.com/spring-projects/spring-petclinic.git
synced 2025-07-19 06:15:50 +00:00
add tests for logging class
This commit is contained in:
parent
0a43a7a311
commit
c037c698a7
2 changed files with 64 additions and 6 deletions
|
@ -7,28 +7,38 @@ import org.slf4j.Logger;
|
|||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
public class LoggingAspect {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
|
||||
|
||||
@FunctionalInterface
|
||||
private interface MethodLogger {
|
||||
void log(String className, String methodName, long executionTime);
|
||||
}
|
||||
|
||||
private final MethodLogger defaultLogger = (className, methodName, executionTime) ->
|
||||
logger.info("Method {}.{} completed in {} ms", className, methodName, executionTime);
|
||||
|
||||
@Around("execution(* org.springframework.samples.petclinic..*.*(..))")
|
||||
public Object logMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
String methodName = joinPoint.getSignature().getName();
|
||||
String className = joinPoint.getTarget().getClass().getSimpleName();
|
||||
|
||||
logger.info("Начало выполнения метода: {}.{}", className, methodName);
|
||||
Supplier<String> methodInfo = () -> String.format("%s.%s", className, methodName);
|
||||
logger.info("Starting method: {}", methodInfo.get());
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
Object result = null;
|
||||
try {
|
||||
result = joinPoint.proceed();
|
||||
Object result = joinPoint.proceed();
|
||||
return result;
|
||||
} finally {
|
||||
long endTime = System.currentTimeMillis();
|
||||
logger.info("Завершение выполнения метода: {}.{} (время выполнения: {} мс)",
|
||||
className, methodName, (endTime - startTime));
|
||||
long executionTime = System.currentTimeMillis() - startTime;
|
||||
defaultLogger.log(className, methodName, executionTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,48 @@
|
|||
package org.springframework.samples.petclinic;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.slf4j.Logger;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith({SpringExtension.class, MockitoExtension.class})
|
||||
@SpringJUnitConfig
|
||||
public class LoggingAspectTest {
|
||||
|
||||
@Mock
|
||||
private Logger logger;
|
||||
|
||||
@InjectMocks
|
||||
private LoggingAspect loggingAspect;
|
||||
|
||||
@Test
|
||||
public void testLogMethodExecution() throws Throwable {
|
||||
// Создаем тестовый метод для проверки
|
||||
TestService testService = new TestService();
|
||||
|
||||
// Вызываем метод, который должен быть перехвачен аспектом
|
||||
testService.testMethod();
|
||||
|
||||
// Проверяем, что логирование было вызвано
|
||||
verify(logger, atLeastOnce()).info(contains("Starting method:"));
|
||||
verify(logger, atLeastOnce()).info(contains("Method TestService.testMethod completed in"));
|
||||
}
|
||||
|
||||
// Вспомогательный класс для тестирования
|
||||
private static class TestService {
|
||||
public void testMethod() {
|
||||
// Простой метод для тестирования
|
||||
try {
|
||||
Thread.sleep(100); // Имитируем некоторую работу
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue