【问题标题】:Integration tests for AspectJAspectJ 的集成测试
【发布时间】:2017-01-03 15:16:17
【问题描述】:

我正在尝试为自定义方面编写集成测试。这是方面类代码段。

@Aspect
@Component
public class SampleAspect {

    private static Logger log = LoggerFactory.getLogger(SampleAspect.class);

   private int count;

   public int getCount(){
      return count;
   }

    public void setCount(){
      this.count= count;
    }


    @Around("execution(* org.springframework.data.mongodb.core.MongoOperations.*(..)) || execution(* org.springframework.web.client.RestOperations.*(..))")
    public Object intercept(final ProceedingJoinPoint point) throws Throwable {
        logger.info("invoked Cutom aspect");
         setCount(1);
         return point.proceed();

    }

}

因此,只要关节点与切入点匹配,上述方面就会拦截。它工作正常。但我的问题是如何进行集成测试。

我所做的是我在 Aspect 中创建了属性“count”以进行跟踪,并在我的 Junit 中声明它。我不确定这是否很好,或者是否有更好的方法对方面进行集成测试。

这是我所做的 Junit 的 sn-p。我的表现很糟糕,但我希望我为集成测试所做的事情是无法理解的。

@Test
public void testSamepleAspect(){
   sampleAspect.intercept(mockJointPoint);
   Assert.assertEquals(simpleAspect.getCount(),1);
}

【问题讨论】:

  • @kriegaex 你能帮我解决这个问题吗...
  • 我认为您应该将计数变量定义为静态。
  • 我现在有点忙,但我稍后会回答,@karthik。很快:样本方面有一个单例实例化模型,所以成员是否应该是静态的是一个相当哲学的问题。但无论如何,这样做都不是一个好主意,因为它会对方面造成运行时损失,尤其是在广泛应用时。顺便说一句,它也不是线程安全的。此外,你不应该用测试的东西污染你的生产代码。稍后我将提出一个(希望是更好的)解决方案。 :-)

标签: java junit mockito integration-testing aspectj


【解决方案1】:

让我们使用与my answer to the related AspectJ unit testing question中相同的示例代码:

要按方面定位的 Java 类:

package de.scrum_master.app;

public class Application {
    public void doSomething(int number) {
        System.out.println("Doing something with number " + number);
    }
}

待测方面:

package de.scrum_master.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class SampleAspect {
    @Around("execution(* doSomething(int)) && args(number)")
    public Object intercept(final ProceedingJoinPoint thisJoinPoint, int number) throws Throwable {
        System.out.println(thisJoinPoint + " -> " + number);
        if (number < 0)
            return thisJoinPoint.proceed(new Object[] { -number });
        if (number > 99)
            throw new RuntimeException("oops");
        return thisJoinPoint.proceed();
    }
}

您有多种选择,具体取决于您要测试的具体内容:

  1. 您可以运行 AspectJ 编译器并验证其控制台输出(启用编织信息),以确保预期的连接点实际上是编织的,而其他连接点则没有。但这宁愿是对您的 AspectJ 配置和构建过程的测试,而不是真正的集成测试。
  2. 类似地,您可以创建一个新的编织类加载器,加载方面,然后加载一些类(加载时编织,LTW),以便动态检查什么被编织,什么没有。在这种情况下,您宁愿测试切入点是否正确,而不是测试由核心 + 方面代码组成的集成应用程序。
  3. 最后但并非最不重要的一点是,您可以执行正常的集成测试,假设在正确编织核心 + 方面代码后应用程序应该如何运行。如何做到这一点取决于您的具体情况,特别是您的方面为核心代码添加了什么样的副作用。

接下来我将描述选项号。 3.查看上面的示例代码,我们看到以下副作用:

  • 对于小的正数,aspect 会通过 original 参数值传递给被拦截的方法,唯一的副作用是额外的日志输出。
  • 对于负数,aspect 通过 negated 参数值(例如,将 -22 变为 22)传递给被截获的方法,这很好测试。
  • 对于较大的正数,方面会引发异常,从而完全停止执行原始方法。

方面的集成测试:

package de.scrum_master.aspect;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.matches;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.io.PrintStream;

import org.junit.*;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;

import de.scrum_master.app.Application;

public class SampleAspectIT {
    @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();

    private Application application = new Application();

    private PrintStream originalSystemOut;
    @Mock private PrintStream fakeSystemOut;

    @Before
    public void setUp() throws Exception {
        originalSystemOut = System.out;
        System.setOut(fakeSystemOut);
    }

    @After
    public void tearDown() throws Exception {
        System.setOut(originalSystemOut);
    }

    @Test
    public void testPositiveSmallNumber() throws Throwable {
        application.doSomething(11);
        verify(System.out, times(1)).println(matches("execution.*doSomething.* 11"));
        verify(System.out, times(1)).println(matches("Doing something with number 11"));
    }

    @Test
    public void testNegativeNumber() throws Throwable {
        application.doSomething(-22);
        verify(System.out, times(1)).println(matches("execution.*doSomething.* -22"));
        verify(System.out, times(1)).println(matches("Doing something with number 22"));
    }

    @Test(expected = RuntimeException.class)
    public void testPositiveLargeNumber() throws Throwable {
        try {
            application.doSomething(333);
        }
        catch (Exception e) {
            verify(System.out, times(1)).println(matches("execution.*doSomething.* 333"));
            verify(System.out, times(0)).println(matches("Doing something with number"));
            assertEquals("oops", e.getMessage());
            throw e;
        }
    }
}

等等,我们正在通过检查日志输出到 System.out 的模拟实例并确保针对较大的正数抛出预期的异常来准确测试示例方面的三种副作用。

【讨论】:

    【解决方案2】:

    @kriegaex 下面代码的测试用例实现应该是什么

    @Aspect
    @Component
    @Slf4j
    public class SampleAspect {
    
        @Value("${timeout:10}")
        private long timeout;
    
        @Around("@annotation(com.packagename.TrackExecutionTime)")
        public Object intercept( ProceedingJoinPoint point) throws Throwable {
    
            long startTime = System.currentTimeMillis();
    
            Object obj = point.proceed();
    
            long endTime  = System.currentTimeMillis();
    
            long timeOut = endTime-startTime;
    
            if(timeOut > timeout) 
             {
              log.error("Error occured");
            }
              return obj;
        }
    }
    

    链接:Junit-integration test for AOP Spring

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多