测试 Spring AOP 方面
在编写方面时,我如何测试它们是否匹配以及它们是否在我想要的时候被调用?
我在 Spring 2.5.6 中使用 @Aspect
声明。
我不关心功能,而是以其他方式提取和测试。
When writing aspects, how can I test that they do match and that they are invoked when I want them to?
I'm using @Aspect
declarations with Spring 2.5.6.
I don't care about the functionality, that's extracted and tested otherwise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我最终通过以下方式创建了一些集成测试:
创建了一个 Spring 感知的 JUnit 测试
为此测试创建了一个 spring 配置,其中:
声明一个应该由方面选取的bean
在单元测试中,我检索虚拟服务并调用其方法
I ended up creating something which is a bit of an integration test, in the following way:
Created a Spring-aware JUnit test
Created a spring configuration for this test which:
declares a bean which should be picked up by the aspect
In the unit test I retrieve the dummy service and invoke its methods
这里需要测试三件不同的事情:
要测试切入点,您可以定义一些与预期的“真实”目标具有相同包/类型/方法签名的测试类型,然后针对切入点定义测试建议以确保它们匹配(还定义一些应该'不进行匹配以确保切入点不会太自由)。 我通常通过定义建议来回调测试目标中的方法、设置标志,然后断言已设置标志来实现此目的。
测试建议比较棘手。 我倾向于将所有建议主体委托给普通方法,然后专注于测试方法而不是建议。
如果您已经这样做了,唯一缺少的部分是您的建议将应用于正确的切入点并实际调用方法。 如果您担心这可能是一个问题,您可以通过创建与您的建议执行相匹配的另一个方面来实现此目的,并设置一个标志以显示该方面调用了预期的委托方法,然后重写该方法什么也不做。
There's three different things to test here:
To test the pointcuts, you can define some test types that have the same package/type/method signatures as the intended "real" targets, then define a test advice against the pointcuts to ensure they are matched (also define some types that shouldn't be matched to ensure the pointcuts aren't too liberal). I usually do this by defining the advice to do a callback to a method in the test target, setting a flag, then assert the flag was set.
To test the advice is trickier. I tend to delegate all the advice body to a normal method, then focus on testing the method rather than the advice.
If you've done that, the only missing part is that your advice is applied to the correct pointcuts and actually calls the methods. If you're concerned this might be a problem you can do this by creating another aspect that matches your advice execution and sets a flag to show the expected delegated method was invoked by the aspect, and override the method to do nothing.