我正在使用Wiremock模拟两个端点。我们的部署Smoketest会在应用程序上调用第三个诊断端点,以测试主要端点的运行状况。我需要让Smoketest端点检查其他两个端点是否正常运行,返回200表示成功,否则返回其他值。对于单个端点 OR 来说,这似乎要么是针对两个可能的结果进行存根,要么根本不使用存根。我在Wiremock中找不到可以发出响应的回调机制,但这似乎正是我所需要的。
我如何在Wiremock中做到这一点?
答案 0 :(得分:0)
答案是将ResponseDefinitionTransformer
子类化并将条件功能构建到transform
覆盖中,该覆盖将返回ResponseDefinition
。
然后,您需要将ResponseDefinitionTransformer
子类的实例传递给WireMockConfiguration装饰器extensions
。
如果不将转换器应用于所有路由,则必须重写ResponseDefinitionTransformer.applyGlobally
以返回false
,并将转换器的名称传递给ResponseDefinitionBuilder
装饰器withTransformers
。
以下是一些Scala演示了这一点:
class RouteStubTransformer extends ResponseDefinitionTransformer {
override def transform(
request: Request,
responseDefinition: ResponseDefinition,
files: FileSource,
parameters: Parameters): ResponseDefinition = {
if (someGoodCondition) {
new ResponseDefinitionBuilder()
.withHeader("Content-Type", "text/plain; charset=UTF-8")
.withStatus(200)
.withBody("""{"message":"ok"}""")
.build()
} else {
new ResponseDefinitionBuilder()
.withHeader("Content-Type", "text/plain; charset=UTF-8")
.withStatus(404)
.withBody("""{"message":"page not found"}""")
.build()
}
}
override def getName: String = "stub-transformer"
override def applyGlobally: Boolean = false
}
object WireMockApp {
val routeStubTransformer = new RouteStubTransformer
val wireMockConfiguration = WireMockConfiguration
.options()
.port(8080)
.extensions(routeStubTransformer)
val server = new WireMockServer(wireMockConfiguration)
server.start()
server.stubFor(get("/route/to/transform").willReturn(aResponse().withTransformers(routeStubTransformer.getName)))
}