Search code examples
scalaakkaakka-testkit

Test Message Adapters in Akka Typed


I am using Akka Typed (version 2.6.8) and I developed an actor that uses a message adapter.

object EncoderClient {
sealed trait Command
final case class KeepASecret(secret: String) extends Command
private final case class WrappedEncoderResponse(response: Encoded) extends Command

def apply(encoder: ActorRef[Encode]): Behavior[Command] =
  Behaviors.setup { context =>
    val encoderResponseMapper: ActorRef[Encoded] =
      context.messageAdapter(response => WrappedEncoderResponse(response))
    Behaviors.receiveMessage {
      case KeepASecret(secret) =>
        encoder ! Encode(secret, encoderResponseMapper)
        Behaviors.same
      case WrappedEncoderResponse(response) =>
        context.log.info(s"I will keep a secret for you: ${response.payload}")
        Behaviors.same
    }
  }
}

I want to test the effect of creation of the Message Adapter. I see that there is a class in the testkit library, MessageAdapter that seems to be a perfect fit to my needs.

However, I can't find anywhere an example of how to use it. Any help?


Solution

  • I found a solution to my problem. If you're interested in testing if a message adapter is created by an actor for a particular type T, then you can use the BehaviorTestKit.expectEffectPF method.

    It follows an example:

    "EncoderClient" should "send an encoding request to the encode" in {
      val encoder = TestInbox[Encode]()
      val client = BehaviorTestKit(EncoderClient(encoder.ref))
      client.run(KeepASecret("My secret"))
      client.expectEffectPF {
        case MessageAdapter(clazz, _) if clazz == classOf[Encoded] =>
      }
    }
    

    If the object clazz is not of the tested type, the test fails.

    Instead, if you're interested in testing that the message adapter works correctly, then, use the strategy suggested by johanandren.