【问题标题】:AspectJ not executing on Junit methodsAspectJ 未在 Junit 方法上执行
【发布时间】:2019-08-01 10:00:32
【问题描述】:

使用 AOP,我试图记录测试方法的执行时间,但是当我运行测试方法时没有任何反应。

我尝试更改切入点中的正则表达式,但似乎不起作用。

我的方面类:

@Aspect
@Component
public class LoggableAspect {

  @Pointcut("execution(public * com.mozzartbet.*.*.*Test.*(..))")
  public void publicTestMethod() {}

  @Around("publicTestMethod() && @annotation(loggable)")
  public Object logTestExecutionTime(ProceedingJoinPoint joinPoint, Loggable loggable) throws Throwable {
    long t1 = System.currentTimeMillis();

    Logger logger = LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName());
    StringBuilder prefix = new StringBuilder(joinPoint.getSignature().getName()).append("()");

    Object result = null;

    try {
      if (loggable.detail()) {
        prefix.append(": ").append(Joiner.on(",").join(joinPoint.getArgs()));
      }
      result = joinPoint.proceed();

      return result;
    } finally {
      long t2 = System.currentTimeMillis();
      if (loggable.detail()) {
        prefix.append(" -> ").append(result);
      }
      logger.info("{} took {} ms", prefix, t2 - t1);
    }
  }
}

我的测试课:

package com.mozzartbet.gameservice.services.impl;

public class PlayerServiceImplTest extends BaseServiceTest {

@Autowired
  private PlayerService playerService;

@Test
  @Loggable(detail = true)
  public void testInsert() {
    assertThat(playerService.insert(Player.builder().id("foo").build()), is(1));
  }

}

注释:

@Retention(RUNTIME)
@Target(METHOD)
public @interface Loggable {

  boolean detail() default false;

}

PlayerService 插入方法

@Override
  public int insert(Player player) {
    try {
      return playerDao.insert(player);
    } catch (DuplicateKeyException e) {
      throw new PlayerException(PlayerExceptionCode.DUPLICATED_PLAYER_ID, "ID: %s is duplicated!", player.getId());
    }
  }

道插入方法:

@Override
  public int insert(Player player) {
    return playerMapper.insert(player);
  }

我是用mybatis插入的。

【问题讨论】:

  • 你需要指定你的自定义注解的限定包名
  • 它在其他方法上没有包名也可以工作,当我尝试添加包名时出现错误。
  • 显示你的 playerService.insert 方法
  • 好的,我已经添加了 playerService.insert 方法的代码。
  • 它是否适用于任何其他测试?您是否尝试仅使用@annotation(loggable) 或简单地使用execution(* *(..)) 来验证AOP 是否已配置为在测试中工作?也许您为应用程序代码正确配置了它,但没有为测试代码配置它。在讨论方面细节之前,让我们先弄清楚这一点。

标签: spring-boot annotations aop aspectj


【解决方案1】:

您的@annotation 定义不正确。

你应该指定注解的限定包名。

@Around("publicTestMethod() && @annotation(your_package.Loggable)")

【讨论】:

  • 它在其他方法上没有包名也可以工作,当我尝试添加包名时出现错误。
  • 不幸的是,这个答案是不正确的。 OP 将注释绑定到通知参数,因此在他的切入点中对参数名称的引用是正确的。如果没有参数绑定,您的答案将是正确的。
最近更新 更多