简体   繁体   中英

How to mock HTTP service within Akka Actor

I have an actor (actually a persistent actor) that, in response to a message (command), needs to make an HTTP call. The question now is how do I deal with this HTTP call in unit test?

Normally I would use the combination of DI and mocking to inject a mock implementation of the HTTP service while testing. But I am not sure if this is how to approach the problem in Akka? Even if this is the how to approach it in Akka, I am not sure how to go about doing the injecting and mocking in testing.

Any thoughts on this? What is the idiomatic way for testing Actors that perform IO operations (HTTP calls, writing to DB etc).

PS: I am using Akka Typed.

My personal belief is that you should avoid IO operations in Actors if at all possible (see this presentation for more details ).

That being said, I'm sure there are people who would disagree and you probably shouldn't listen to me :)

Here is how I would go about mocking it for a test.

  1. Create a trait that represents your http call.

    trait Client { def makeHttpCall(input: Int): Future[Output] }

(You will want to create a class of some kind that implements this trait and test it separately from your actor.)

  1. Pass an instance of that trait into your actor using its constructor/apply method.

    def apply(client: Client): Behavior[...] = { // use your client inside of your behavior }

  2. In your test create a mock instance of Client and pass that in to your actor. You can mock your Client using a mocking library (ScalaMock or Mockito) or you can actually just create a test implementation of your trait with relative ease:

    class TestClient extends Client { def makeHttpCall(input: Int): Future[Output] = Future.successful(Output(...)) }

Note: all of the names for classes and methods that I chose are just placeholders. You should, of course, choose more specific names based on the context you are working in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM