简体   繁体   中英

How to Mock akka Actor for unit Test?

@Singleton
class EventPublisher @Inject() (@Named("rabbit-mq-event-update-actor") rabbitControlActor: ActorRef)
(implicit ctx: ExecutionContext) {

def publish(event: Event): Unit = {
         logger.info("Publishing Event: {}", toJsObject(event), routingKey)
         rabbitControlActor ! Message.topic(shipmentStatusUpdate, routingKey = "XXX")
 }
}

I want to write a unit test to verify if this publish function is called

rabbitControlActor ! Message.topic(shipmentStatusUpdate, routingKey = "XXX")

is called only once. I am using spingo to publish messages to Rabbit MQ. I am using Playframework 2.6.x and scala 2.12 .

You can create an TestProbe actor with:

val myActorProbe = TestProbe()

and get its ref with myActorProbe.ref

After, you can verify that it receives only one message with:

myActorProbe.expectMsg("myMsg")
myActorProbe.expectNoMsg()

You probably should take a look at this page: https://doc.akka.io/docs/akka/2.5/testing.html

It depends you want to check only the message is received by that actor or you want to test the functionality of that actor. If you want to check message got delivered to the actor you can go with TestProbe. Ie

val probe = TestProbe()
probe.ref ! Message

Then do :

probe.expectMsg[Message]

You can make use of TestActorRef in case where you have supervisor actor, which is performing some db operations so you can over ride its receive method and stop the flow to go till DB. Ie

val testActor =new TestActorRef(Actor.props{
override receive :Receive ={
case m:Message => //some db operation in real flow 
//in that case you can return what your actor return from the db call may be some case class. 
case _ => // do something }})

Assume your method return Future of Boolean.

val testResult=(testActor ? Message).mapTo[boolean]
//Then assert your result

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