user1332148
user1332148

Reputation: 1346

How do I intercept Wiremock requests and conditionally issue a response?

I am using Wiremock to mock out two endpoints. Our deployment smoketest calls a third, diagnostic, endpoint on the app to test the health of the primary endpoints. I need to have the smoketest endpoint check that the other two endpoints are functioning, return a 200 for success and something else if not. This seems to be either stubbing out two possible results for a single endpoint OR not use stubbing at all. I can't find a callback mechanism in Wiremock that can issue the response but that seems to be what I need.

How do I do this in Wiremock?

Upvotes: 0

Views: 3176

Answers (1)

user1332148
user1332148

Reputation: 1346

The answer is to subclass ResponseDefinitionTransformer and build the conditional functionality into the transform override, which returns a ResponseDefinition.

You then need to pass an instance of the ResponseDefinitionTransformer subclass to the WireMockConfiguration decorator extensions.

If the transformer is not to be applied to every route you must override ResponseDefinitionTransformer.applyGlobally to return false and pass the name of the transformer to the ResponseDefinitionBuilder decorator withTransformers.

Here is some Scala that demonstrates this:

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)))
}

Upvotes: 2

Related Questions