如何在Quarkus测试中使用Mockito监视Interceptor类
问题:Quarkus单元测试中无法监视Interceptor的方法
我在单元测试中尝试监视org.acme.LoggingInterceptor类的org.acme.LoggingInterceptor#log(java.lang.String)方法,该Interceptor类代码如下:
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); } }
我在Quarkus测试中分别尝试使用@InjectSpy和直接调用Mockito.spy(..)创建spy,两种方式均失败:
方式1:使用@InjectSpy失败
测试初始化即报错:
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
对应测试代码:
@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:使用Mockito.spy(..)失败
运行提示:
Wanted but not invoked: loggingInterceptor.log();
对应测试代码:
@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()); } }
内容的提问来源于stack exchange,提问作者syr
相关产品推荐
相关产品推荐

