복붙노트

[SPRING] 단위 테스트 Spring @ AOP 방식의 메소드

SPRING

단위 테스트 Spring @ AOP 방식의 메소드

Spring "stuff"를 할 필요없이 대부분의 Spring 클래스를 단위 테스트 할 수 있습니다.

나는 단위 테스트를 할 수있다 @ 전에 스프링을 사용하지 않고 조언 방법 :

예제 코드 :

@Before("execution(* run(..)) && " + "" +
          "target(target) && " +
        "args(name)")
public void logName(Object target, String name) {
    logger.info("{} - run: {}", target, name);
}

예제 테스트 :

@Test
public void testLogName() {
    aspect.setLogger(mockLogger);
    aspect.logName(this,"Barry");
    assertTrue(mockLogger.hasLogged("TestAspect - run: Barry"));
}

그러나 @Around advice는 ProceedingJoinPoint 객체를 처리합니다.

@Around("com.xyz.myapp.SystemArchitecture.businessService()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
   // start stopwatch
   Object retVal = pjp.proceed();
   // stop stopwatch
   return retVal;
 }

ProceedingJoinPoint 개체를 인스턴스화하는 방법을 모르겠습니다. 전체 Spring 애플리케이션 컨텍스트를 시작하지 않고이 클래스를 테스트하려면 어떻게해야합니까?

해결법

  1. ==============================

    1.프로그래밍 방식으로 프록시를 생성하여 Spring Aspect를 테스트 할 수있다.

    프로그래밍 방식으로 프록시를 생성하여 Spring Aspect를 테스트 할 수있다.

    MyInterface target = new MyClass();
    AspectJProxyFactory factory = new AspectJProxyFactory(target);
    MyAspect aspect = new MyAspect(arg);
    factory.addAspect(aspect);
    MyInterface proxy = factory.getProxy();
    

    ... 그러면 프록시에서 메소드를 호출하고 aspect, 프록시 및 대상에 대한 어설 션을 수행 할 수 있습니다.

  2. from https://stackoverflow.com/questions/11436600/unit-testing-spring-around-aop-methods by cc-by-sa and MIT license