samedi 20 août 2016

How to test a mocked actor using the ask pattern?

I have the following class:

class Reporter(@Named("my-actor") val actor: ActorRef){

  implicit val timeout = Timeout(20 seconds)

  override def doSomething(id: Int) = {
      (actor ? id)
         .map(products => products.asInstanceOf[List[Product]])
         .map(products => {
            if (products.isEmpty){
                actor ! NoProducts
            }else{
                actor ! GotProducts(products)
            }
         }
  }
}

I want to test this actor, but I am not sure how to mock, or instruct a mocked actor to return when it get a message.

So I assume the test should look something like this:

class ReporterTest with MockitoSugar{

  val actor = mock[ActorRef]
  val reporter = new Reporter(actor)

  "test" must {
    "no products" in {
      when(actor.asInstanceOf[AskableActorRef].?(10)))
        .thenReturn(Future.successful(List()))
      await(reporter.soSomething(10))
      verify(actor.asInstanceOf[ScalaActorRef], times(0)).!(any[GotProducts])
    }
  }
}

This get compiled, but fails on class cast exception, I guess this is not the right direction. Any idea?

Thanks!

Aucun commentaire:

Enregistrer un commentaire