3

I am using Akka actor system with Spray and WireMock for stubbing web services. I want to also verify that the external http request was already made.

In the following use case a POST request is made to my Spray server which should send a request to an external service:

stubFor(get(urlEqualTo("/external-service"))
    .willReturn(aResponse()
      .withStatus(200)
      .withBodyFile("response-body.json")));

myService ! Post("/my-service", FormData(Seq("id" -> "1")))

Thread.sleep(1000)

verify(postRequestedFor(urlEqualTo("/services/harvesterService")))

In various examples I have seen the Thread.sleep technique, because otherwise the ActorSystem is shut down and my service will never make the http request for the external service.

Is it possible to avoid this? Can WireMock wait for the request to the external service? Possibly with some timeout...

mirelon
  • 4,896
  • 6
  • 40
  • 70

1 Answers1

1

NOTE: This assumes that your actor actually sends an HTTP call when it receives that message. If you want to test directly the Spray routes, I'd suggest you look at http://spray.io/documentation/1.2.3/spray-testkit/ which is the standard way of testing spray routes.

Usually what I do is use ScalaTest together with the Akka/Spray TestKit, and use the eventually function. eventually allows you to repeatedly check for a condition that eventually will happen. If you catch the exception thrown by the verify method, then you can assert that the post has actually been sent or not. You could use something like

def postHasBeenSent(url: String): Boolean = 
  try {
    verify(postRequestedFor(urlEqualTo(url)))
    true
  } catch {
    case e: VerificationException => false
  }

(you can also use Try monad if you want there, but that's not the point here!)

And then in your test (assuming you're using matchers):

myService ! Post("/my-service", FormData(Seq("id" -> "1")))

eventually {
  postHasBeenSent("/my-service") shouldBe true
}

You can find more about eventually and all the goodies that come with it (for example polling intervals) at http://doc.scalatest.org/2.2.6/index.html#org.scalatest.concurrent.Eventually

manub
  • 3,990
  • 2
  • 24
  • 33