【问题标题】:webTarget.request returns type not acceptable by builder.methodwebTarget.request 返回的类型不被builder.method 接受
【发布时间】:2018-04-28 17:03:52
【问题描述】:

我正在尝试对 API REST 函数进行单元测试。

    builder = webTarget.request();

返回类型的builder

javax.ws.rs.client.Invocation.Builder

但是,如果我使用该构建器并在其上调用 builder.method("POST", entity),则调用的方法如下所示:

    public Response method(final String name, final Entity<?> entity) throws ProcessingException {
        requestContext.setMethod(name);
        storeEntity(entity);
        return new JerseyInvocation(this).invoke();
    }

最后一行用作“this”不同的构建器:

org.glassfish.jersey.client.JerseyInvocation.Builder

并且在那条线上运行失败。

我看着它,感觉自己疯了:怎么可能,函数被调用为一个类的成员,但是当在那个方法中使用“this”时,使用的是完全不同的类?

【问题讨论】:

    标签: java eclipse rest unit-testing jersey


    【解决方案1】:

    InvocationInvocation.Builder 都是接口。 WebTarget.request() 合约将返回 Invocation.Builder。这些都是我们这里说的接口; WebTargetInvocationInvocation.Builder。这是 JAX-RS 规范的契约设计。由 JAX-RS 实现来实现这些接口。 Jersey 的实现分别是 JerseyWebTargetJerseyInvocationJerseyInvociation.Builder

    如果我创建了这样的东西也是一样的

    public interface Model {}
    
    public interface Service {
        Model getModel();
    }
    
    public ModelImpl implements Model {}
    
    public class ServiceImpl implements Service {
        @Override
        public Model getModel() {
            return new ModelImpl();
        }
    }
    

    这里没有什么特别的地方。 Service 合约说getModel() 方法返回一个Model,它是一个接口,实际返回值将是ModelImpl 类型的实现。作品中的多态性。

    【讨论】:

    • 那么,我应该将 'builder' 声明为 JerseyInvocation.Builder,然后 builder.method 就可以工作了吗?
    • 不,Invocation.Builder 很好。没有理由它不应该工作。这是基本的 Java 东西。与泽西岛无关。
    • 您是否遇到了某种错误?我不确定你的问题到底是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 2019-08-21
    • 1970-01-01
    相关资源
    最近更新 更多