【发布时间】:2014-08-06 17:18:07
【问题描述】:
我在JBoss documentation之后创建了一个拦截器。
为了测试拦截器,我输入:
@Interceptor
@Transactional
public class TransactionalInterceptor {
@AroundInvoke
public Object intercept(InvocationContext ctx) throws Exception {
System.out.println("intercept!");
return ctx.proceed();
}
}
现在我想在单元测试中测试这个拦截器,使用the WeldJUnit4Runner class。
@RunWith(WeldJUnit4Runner.class)
public class MyTest {
@Test
@Transactional // the interceptor I created
public void testMethod() {
System.out.println("testMethod");
anotherMethod();
}
@Transactional
public void anotherMethod() {
System.out.println("anotherMethod");
}
}
现在预期的输出当然是
intercept!
testMethod
intercept!
anotherMethod
但是,输出却是
intercept!
testMethod
anotherMethod
主要问题是,如果我将一个 bean 注入到我的测试中,这也是如此:我调用的 bean 的第一个方法被拦截,但如果此方法调用另一个方法,则不会调用拦截器。
非常感谢任何想法!
我只是尝试按照@adrobisch 的建议修改我的代码,这很有效:
@RunWith(WeldJUnit4Runner.class)
public class MyTest {
@Inject
private MyTest instance;
@Test
@Transactional // the interceptor I created
public void testMethod() {
System.out.println("testMethod");
instance.anotherMethod();
}
@Transactional
public void anotherMethod() {
System.out.println("anotherMethod");
}
}
输出是(如预期的那样)
intercept!
testMethod
intercept!
anotherMethod
但是,以下操作不起作用:
@RunWith(WeldJUnit4Runner.class)
public class MyTest {
@Inject
private MyTest instance;
@Test
// @Transactional <- no interceptor here!
public void testMethod() {
System.out.println("testMethod");
instance.anotherMethod();
}
@Transactional
public void anotherMethod() {
System.out.println("anotherMethod");
}
}
这里的输出是
testMethod
anotherMethod
不过,这似乎符合规范!现在一切都很好。
【问题讨论】:
-
我对您编辑中的行为进行了一些研究,我认为从 CDI 的角度来看,从
testMethod调用anotherMethod被视为业务方法调用,因此不应用拦截器。请参阅 github.com/cdi-spec/cdi-spec.org/blob/master/_faq/core/… 以获取更多参考信息和 CDI 规范的链接。