gpt4 book ai didi

java - 单元测试编译时织入

转载 作者:行者123 更新时间:2023-11-29 08:53:01 24 4
gpt4 key购买 nike

我正在使用 aspectj maven plugin在编译时编织方面。当我运行应用程序时,带有 @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 注释的方法,“creating MyAdviceClass”将在第一次调用该方法时打印,并且每次都会打印“timed annotation called”。

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

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

最佳答案

我已经找到了解决方案,并希望将其发布给遇到此问题的其他人。诀窍是在您的 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 .

关于java - 单元测试编译时织入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21737206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com