2

我正在使用aspectj maven 插件在编译时编织 Aspects。当我运行应用程序时,带有@Advice注释的类在第一次调用通知之前被实例化。例如:

@Aspect
public class MyAdviceClass {

    public MyAdviceClass() {
        System.out.println("creating MyAdviceClass");
    }

    @Around("execution(* *(..)) && @annotation(timed)")
    public Object doBasicProfiling(ProceedingJoinPoint pjp, Timed timed) throws Throwable {
        System.out.println("timed annotation called");
        return pjp.proceed();
    }
}

如果我有一个使用@Timed注释的方法,则第一次调用该方法时将打印“创建 MyAdviceClass”,并且每次都会打印“调用的定时注释”。

我想通过模拟一些组件来对建议的功能进行单元测试,MyAdviceClass但是不能这样做,因为MyAdviceClass它是由 AspectJ 及时实例化的,而不是通过 Spring Beans。

像这样进行单元测试的最佳实践方法是什么?

4

1 回答 1

0

我找到了解决方案,并希望将其发布给遇到此问题的任何其他人。诀窍是factory-method="aspectOf"在你的 spring bean 定义中使用。因此,使用上面的示例,我会将这一行添加到我的applicationContext.xml

<bean class="com.my.package.MyAdviceClass" factory-method="aspectOf"/>

我的任何单元测试看起来都像这样:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/META-INF/spring/applicationContext.xml")
public class MyAdviceClassTest {
    @Autowired private MyAdviceClass advice;
    @Mock private MyExternalResource resource;

    @Before
    public void setUp() throws Exception {
        initMocks(this);
        advice.setResource(resource);
    }

    @Test
    public void featureTest() {
        // Perform testing
    }
}

更多详细信息可在此处获得。

于 2014-02-13T19:22:49.290 回答