quarkus测试中如何用mockito监视拦截器类

lmyy7pcs  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(125)

在单元测试中,我尝试监视以下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

t5zmwmid

t5zmwmid1#

这里的第一个错误是拦截器被注解为@ApplicationScoped。引用CDI规范:
拦截器的示例是它们拦截的bean示例的依赖对象。
当存在这种不正确的拦截器时,较新版本的Quarkus实际上将失败部署,以满足以下规则:
如果拦截器声明了除@Dependent以外的任何作用域,容器会自动检测到问题,并将其视为定义错误。
其次,@InjectMock@InjectSpy机制只适用于普通的作用域bean,如www.example.com所述https://quarkus.io/guides/getting-started-testing#quarkus_mock(这是因为对于普通的作用域bean,注入的不是一个“实际”示例,而是一个客户端代理,负责查找示例--这也是模拟的方式)。
由于拦截器从来都不是正常的作用域,@InjectMock@InjectSpy不能为它们工作。

相关问题