mercredi 18 novembre 2015

Akka Actors unit testing for dummies

I'm newbie in Akka and Scala and i come from a non-concurrent world. Probably i'm doing a lot of things wrong, i will appreciate feedback even it's not related to the question.

I'm doing a simple chat application with Akka and Scala. I started (bc business requirements) by "typing feature"... it's the typical feature in whatsapp or tellegram "John is typing a message".

I have modelled it by two actors types: Talkers and Conversation and I want to unit test my Conversation actor. My Conversation actor looks like:

object Conversation {
  def props(conversationId: UUID, talkers: List[ActorRef])(out: ActorRef) = Props(new Conversation(conversationId, talkers))

  case class Typing(talkerId: TalkerId)
}

class Conversation(conversationId: UUID, talkers: List[ActorRef]) extends Actor with ActorLogging {
  def receive = LoggingReceive {
    case Typing(talkerId) =>
      // notify all talkers that a talker is typing
      // @TODO don't notify user which is typing
      talkers foreach {talker: ActorRef => talker ! InterlocutorTyping(talkerId)}
 }
}

I think, by now is very simple. So, before start coding in Scala and Akka I had tested this like:

  • I get my Conversation actor
  • I mock talkers
  • I send a message Typing to my actor
  • I expect that talkers should be notified

I don't really know if it's the correct approach in Scala and Akka. My test (using scalatest) looks like this:

"Conversation" should {
"Notify interlocutors when a talker is typing" in {
  val talkerRef1 = system.actorOf(Props())
  val talkerRef2 = system.actorOf(Props())

  val talkerRef1Id = TalkerIdStub.random

  val conversationId = UUID.randomUUID()

  val conversationRef = system.actorOf(Props(classOf[Conversation], conversationId, List(talkerRef1, talkerRef2)))

  // should I use TestActorRef ?

  conversationRef ! InterlocutorTyping(talkerRef1Id)

  // assert that talker2 is notified when talker1 is typing
}
}

  1. Should I use TestActorRef? Should I use TestProbe() (I read that this is for integration tests)

  2. How can I create Talker mocks? Is this approach correct?

  3. It's correct to inject a List of Talkers to my conversation Actor?

I searched for documentation, but I think there are a lot too old and I'm not sure if the code examples are still functional.

Thank you for your time guys, and sorry about this noob question :=)

Aucun commentaire:

Enregistrer un commentaire