在单元测试中,我尝试监视以下intceptor类,方法org.acme.LoggingInterceptor#log(java.lang.String)
package org.acme;
import javax.enterprise.context.ApplicationScoped;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import io.quarkus.arc.Priority;
import io.quarkus.logging.Log;
@Logging
@Priority(10)
@Interceptor
@ApplicationScoped
public class LoggingInterceptor {
@AroundInvoke
Object log(InvocationContext ctx) throws Exception {
log("inside LoggingInterceptor @AroundInvoke");
return ctx.proceed();
}
public void log(String message) {
Log.info(message);
}
}
我尝试通过@InjectSpy
进行quarkus测试,也尝试通过Mockito.spy(..)
直接在测试中创建spy。
1st:创建测试时已失败,错误:无效使用io.quarkus.test.junit.mockito.InjectSpy -无法解析以下类型的bean:org.acme.LoggingInterceptor.违规字段为测试类org. acme. LoggingInterceptor Test1_Subclass的loggingInterceptor
@QuarkusTest
public class LoggingInterceptorTest1 {
//FIXME fails with: Invalid use of io.quarkus.test.junit.mockito.InjectSpy - could not resolve the bean of type: org.acme.LoggingInterceptor. Offending field is loggingInterceptor of test class class org.acme.LoggingInterceptorTest1_Subclass
@InjectSpy
LoggingInterceptor loggingInterceptor;
@Test
public void test() ...
第2次:失败:被通缉但未被援引:int getName();
@QuarkusTest
public class LoggingInterceptorTest2 {
@Test
public void testAroundInvoke() {
LoggingInterceptor loggingInterceptor = Mockito.spy(LoggingInterceptor.class);
serviceMethodWithInterceptor();
ArgumentCaptor<String> logMessageCaptor = ArgumentCaptor.forClass(String.class);
Mockito.verify(loggingInterceptor).log(logMessageCaptor.capture());
//FIXME fails with: Wanted but not invoked: loggingInterceptor.log(<Capturing argument>);
assertEquals("inside LoggingInterceptor @AroundInvoke", logMessageCaptor.getValue());
}
示例项目:https://github.com/syr/quarkus-resteasy-postgres/tree/spy_on_interceptor
1条答案
按热度按时间t5zmwmid1#
这里的第一个错误是拦截器被注解为
@ApplicationScoped
。引用CDI规范:拦截器的示例是它们拦截的bean示例的依赖对象。
当存在这种不正确的拦截器时,较新版本的Quarkus实际上将失败部署,以满足以下规则:
如果拦截器声明了除
@Dependent
以外的任何作用域,容器会自动检测到问题,并将其视为定义错误。其次,
@InjectMock
和@InjectSpy
机制只适用于普通的作用域bean,如www.example.com所述https://quarkus.io/guides/getting-started-testing#quarkus_mock(这是因为对于普通的作用域bean,注入的不是一个“实际”示例,而是一个客户端代理,负责查找示例--这也是模拟的方式)。由于拦截器从来都不是正常的作用域,
@InjectMock
和@InjectSpy
不能为它们工作。