Scala 中的 Wiremock 2.x

Wiremock 2.x in Scala

我正在尝试使用 Scala 的 Wiremock 2.1.6。但是,映射构建器的类型发生了一些变化,因此 scalac 无法再对其进行类型检查。

文档中的第一个存根示例:

stubFor(get(urlEqualTo("/some/thing"))
        .willReturn(aResponse()
            .withHeader("Content-Type", "text/plain")
            .withBody("Hello world!")));

编译时出现这个错误:

type mismatch;
    found   : ?0(in value <local TestSpec>) where type ?0(in value <local TestSpec>) <: AnyRef
    required: com.github.tomakehurst.wiremock.client.RemoteMappingBuilder[_ <: AnyRef, _ <: com.github.tomakehurst.wiremock.client.ScenarioMappingBuilder]
    get(urlEqualTo("some/thing")).willReturn(

方法willReturn定义在RemoteMappingBuilder接口

public interface RemoteMappingBuilder<M extends RemoteMappingBuilder, S extends ScenarioMappingBuilder> {
    ...
    M willReturn(ResponseDefinitionBuilder responseDefBuilder);
}

在我看来,Scala 对在 M extends RemoteMappingBuilder.

中使用没有类型参数的通用接口 RemoteMappingBuilder 并不满意

关于如何解决这个问题有什么建议吗?

您应该像这样转换为 RemoteMappingBuilder[_,_]

stubFor(get(urlEqualTo("/some/thing"))
    .willReturn(aResponse()
        .withHeader("Content-Type", "text/plain")
        .withBody("Hello world!")).asInstanceOf[RemoteMappingBuilder[_,_]])

不幸的是,每次调用通用 RemoteMappingBuilder 接口的函数时都需要这样做,例如:

stubFor(get(urlEqualTo("/some/thing"))
    .withQueryParam("some_parameter", equalTo(paramValue)).asInstanceOf[RemoteMappingBuilder[_,_]]
    .willReturn(aResponse()
        .withHeader("Content-Type", "text/plain")
        .withBody("Hello world!")).asInstanceOf[RemoteMappingBuilder[_,_]])

这已在最新版本中修复:https://github.com/tomakehurst/wiremock/pull/482