单元测试编译时编织

时间:2014-02-12 19:01:44

标签: java spring junit aspectj aspectj-maven-plugin

我在编译时使用aspectj maven plugin编织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实现。

单位测试的最佳实践方法是什么?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,并希望将其发布给遇到此问题的其他任何人。诀窍是在spring bean定义中使用factory-method="aspectOf"。因此,使用上面的示例,我会将此行添加到我的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
    }
}

有更多详情可供here

相关问题