我碰到一篇有趣的文章。AOP Aspects as mocks in JUnit
由于我需要模拟多个最终和私有静态变量,因此我计划使用aop代替反射或powermockito,因为它们会引起SpringJunit4runner问题。
有任何方法,我可以将@Aspect用于测试类,而无需使用注释@EnableAspectJAutoProxy(我希望方面仅在一个测试用例中用于类X)
这是示例,我想做。问题得到了回答(正在讨论可以做什么)
//External class
public final class ABC(){
public void method1() throws Exception{
}
}
@Service
public void DestClass(){
private static finla ABC abc = new ABC();
public Object m(){
//code
....
try{
abc.method1();
}
catch(Exception e){
//Do Something
//Return null
return null;
}
//more code
....
}
Spring框架允许以编程方式创建建议目标对象的代理,而无需通过@EnableAspectJAutoProxy
或<aop:aspectj-autoproxy>
进行配置>
详细信息可以在文档部分找到:Programmatic Creation of @AspectJ Proxies,实现非常简单。
文档中的示例代码。
// create a factory that can generate a proxy for the given target object AspectJProxyFactory factory = new AspectJProxyFactory(targetObject); // add an aspect, the class must be an @AspectJ aspect // you can call this as many times as you need with different aspects factory.addAspect(SecurityManager.class); // you can also add existing aspect instances, the type of the object supplied must be an @AspectJ aspect factory.addAspect(usageTracker); // now get the proxy object... MyInterfaceType proxy = factory.getProxy();
请注意,使用Spring AOP时,只能建议方法执行。摘录自documentation
Spring AOP当前仅支持方法执行连接点(建议在Spring bean上执行方法)。领域尽管支持现场,但并未实施拦截可以在不破坏核心Spring AOP API的情况下添加拦截功能。如果您需要建议现场访问和更新连接点,请考虑语言,例如AspectJ。
与该问题共享的文档是关于Aspectj的,并且在没有提供示例代码的情况下,很难推断出是否可以通过Spring AOP实现需求。该文档也提到了这一点。
AspectJ集成的一个示例是Spring框架,现在可以在其自己的AOP中使用AspectJ切入点语言实施。 Spring的实现并非专门针对作为测试解决方案
。希望这会有所帮助。