SlideShare ist ein Scribd-Unternehmen logo
1 von 17
Downloaden Sie, um offline zu lesen
Testing Akka ActorsTesting Akka Actors
Piyush Mishra
Software Consultant
Knoldus Software LLP
Piyush Mishra
Software Consultant
Knoldus Software LLP
Topics CoveredTopics Covered
Basics of Akka
Settings in build.sbt
Defining an of Akka Actor
Creation of Akka Actor
ActorRef
Testing Akka Actors
Integration testing using testkit
Basics of Akka
Settings in build.sbt
Defining an of Akka Actor
Creation of Akka Actor
ActorRef
Testing Akka Actors
Integration testing using testkit
What is AkkaWhat is Akka
Akka is framework for writing event driving, concurrent,
fault-tolerant and scalable application.
a) It uses actor model to build concurrent, fault-tolerant
and scalable application.
b) Actors are the higher abstraction for concurrency and
parallelism.
c) They are very lightweight event-driven processes
(approximately 2.7 million actors per GB RAM).
d) Akka provides supervisor stategy to build fault tolerance
Applications.
Akka is framework for writing event driving, concurrent,
fault-tolerant and scalable application.
a) It uses actor model to build concurrent, fault-tolerant
and scalable application.
b) Actors are the higher abstraction for concurrency and
parallelism.
c) They are very lightweight event-driven processes
(approximately 2.7 million actors per GB RAM).
d) Akka provides supervisor stategy to build fault tolerance
Applications.
Settings in build.sbtSettings in build.sbt
In order to test Akka actors we need to add following two
dependencies in build.scala or build.sbt
libraryDependencies ++= Seq(
"com.typesafe.akka" % "akka-actor" % "2.0.5",
"com.typesafe.akka" % "akka-testkit" % "2.0.5")
In order to test Akka actors we need to add following two
dependencies in build.scala or build.sbt
libraryDependencies ++= Seq(
"com.typesafe.akka" % "akka-actor" % "2.0.5",
"com.typesafe.akka" % "akka-testkit" % "2.0.5")
Defining an Akka actorDefining an Akka actor
package com.Testing
import akka.actor.Actor
class SimpleActor extends Actor {
def receive = {
case msg: String =>
case _ => println("Got other than string")
}
}
package com.Testing
import akka.actor.Actor
class SimpleActor extends Actor {
def receive = {
case msg: String =>
case _ => println("Got other than string")
}
}
Creating an actorCreating an actor
package com.Testing
import akka.actor.ActorSystem
import akka.actor.Props
object CreateActor extends App {
val system = ActorSystem("testing")
val actor = system.actorOf(Props[SimpleActor])
actor ! "hello"
}
package com.Testing
import akka.actor.ActorSystem
import akka.actor.Props
object CreateActor extends App {
val system = ActorSystem("testing")
val actor = system.actorOf(Props[SimpleActor])
actor ! "hello"
}
What is ActorRefWhat is ActorRef
ActorRef is the Immutable and serializable handle to an actor
which may or may not reside on the local host or inside the
same ActorSystem .
We can not call methods on actorRef.
ActorRef is the Immutable and serializable handle to an actor
which may or may not reside on the local host or inside the
same ActorSystem .
We can not call methods on actorRef.
Testing with TestActorRefTesting with TestActorRef
This special type of reference is designed specifically for test
purposes and allows access to the actor in two ways: either
by obtaining a reference to the underlying actor instance, or
by invoking or querying the actor's behaviour (receive).
This special type of reference is designed specifically for test
purposes and allows access to the actor in two ways: either
by obtaining a reference to the underlying actor instance, or
by invoking or querying the actor's behaviour (receive).
Obtaining a Reference to an ActorObtaining a Reference to an Actor
import akka.testkit.TestActorRef
val actorRef = TestActorRef[MyActor]
val actor = actorRef.underlyingActor
import akka.testkit.TestActorRef
val actorRef = TestActorRef[MyActor]
val actor = actorRef.underlyingActor
Testing the Actor's BehaviorTesting the Actor's Behavior
implicit val timeout = Timeout(5 seconds)
implicit val system = ActorSystem("Unit")
val actorRef = TestActorRef(new SimpleActor)
val result = Await.result((actorRef ? 42), 5
seconds).asInstanceOf[Int]
result must be(42)
implicit val timeout = Timeout(5 seconds)
implicit val system = ActorSystem("Unit")
val actorRef = TestActorRef(new SimpleActor)
val result = Await.result((actorRef ? 42), 5
seconds).asInstanceOf[Int]
result must be(42)
Integration test with TestkitIntegration test with Testkit
Testkit is used for integration testing of an actor. This toolkit
provider a ImplicitSender which is actually a test actor which
dispatches messages to actors under test.
Continued
Testkit is used for integration testing of an actor. This toolkit
provider a ImplicitSender which is actually a test actor which
dispatches messages to actors under test.
Continued
Integration test with TestkitIntegration test with Testkit
class MySpec(_system: ActorSystem) extends TestKit(_system) with
ImplicitSender with WordSpec with MustMatchers with BeforeAndAfterAll {
def this() = this(ActorSystem("MySpec"))
import MySpec._
override def afterAll {
system.shutdown()
}
"An Echo actor" must {
"send back messages unchanged" in {
val echo = system.actorOf(Props[EchoActor])
echo ! "hello world"
expectMsg("hello world")
}
class MySpec(_system: ActorSystem) extends TestKit(_system) with
ImplicitSender with WordSpec with MustMatchers with BeforeAndAfterAll {
def this() = this(ActorSystem("MySpec"))
import MySpec._
override def afterAll {
system.shutdown()
}
"An Echo actor" must {
"send back messages unchanged" in {
val echo = system.actorOf(Props[EchoActor])
echo ! "hello world"
expectMsg("hello world")
}
Timing AssertionsTiming Assertions
Timing: certain events must not happen immediately (like a timer), others need
to happen before a deadline.
The block given to within must complete after a Duration which is between min
and max, where the former defaults to zero. The deadline calculated by adding
the max parameter to the block's start time is implicitly available within the block
to all examination methods
Timing: certain events must not happen immediately (like a timer), others need
to happen before a deadline.
The block given to within must complete after a Duration which is between min
and max, where the former defaults to zero. The deadline calculated by adding
the max parameter to the block's start time is implicitly available within the block
to all examination methods
Timing AssertionsTiming Assertions
class Timing(_system: ActorSystem) extends TestKit(_system) with
ImplicitSender with MustMatchers with WordSpec {
def this() = this(ActorSystem("MySpec"))
import MySpec._
"An simple actor" must {
"send reply within 2 seconds" in {
val worker = system.actorOf(Props[SimpleActor])
within(200 millis) {
worker ! 4
expectMsg(4)
expectNoMsg // will block for the rest of the 200ms
Thread.sleep(300) // will NOT make this block fail
}
}
}
}
class Timing(_system: ActorSystem) extends TestKit(_system) with
ImplicitSender with MustMatchers with WordSpec {
def this() = this(ActorSystem("MySpec"))
import MySpec._
"An simple actor" must {
"send reply within 2 seconds" in {
val worker = system.actorOf(Props[SimpleActor])
within(200 millis) {
worker ! 4
expectMsg(4)
expectNoMsg // will block for the rest of the 200ms
Thread.sleep(300) // will NOT make this block fail
}
}
}
}
Using ProbesUsing Probes
When the actors under test are supposed to send various
messages to different destinations. approach is to use it for
creation of simple probe actors to be inserted in the message
flows. To make this more powerful and convenient, there is a
concrete implementation called TestProbe.
The functionality is best explained using a small example
When the actors under test are supposed to send various
messages to different destinations. approach is to use it for
creation of simple probe actors to be inserted in the message
flows. To make this more powerful and convenient, there is a
concrete implementation called TestProbe.
The functionality is best explained using a small example
Using ProbesUsing Probes
class Probe(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with WordSpec
with MustMatchers with BeforeAndAfterAll {
def this() = this(ActorSystem("MySpec"))
import MySpec._
override def afterAll {
system.shutdown()
}
"An DoubleEcho actor" must {
"send reply both probes" in {
val probe1 = TestProbe()
val probe2 = TestProbe()
val actor = system.actorOf(Props[MyDoubleEcho])
actor ! (probe1.ref, probe2.ref)
actor ! "hello"
probe1.expectMsg(500 millis, "hello")
probe2.expectMsg(500 millis, "hello")
}
}
}
class Probe(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with WordSpec
with MustMatchers with BeforeAndAfterAll {
def this() = this(ActorSystem("MySpec"))
import MySpec._
override def afterAll {
system.shutdown()
}
"An DoubleEcho actor" must {
"send reply both probes" in {
val probe1 = TestProbe()
val probe2 = TestProbe()
val actor = system.actorOf(Props[MyDoubleEcho])
actor ! (probe1.ref, probe2.ref)
actor ! "hello"
probe1.expectMsg(500 millis, "hello")
probe2.expectMsg(500 millis, "hello")
}
}
}
ThanksThanks

Weitere ähnliche Inhalte

Was ist angesagt?

Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
Jiayun Zhou
 

Was ist angesagt? (20)

Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit Test
 
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...
 
Client side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karmaClient side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karma
 
Qunit Java script Un
Qunit Java script UnQunit Java script Un
Qunit Java script Un
 
First glance at Akka 2.0
First glance at Akka 2.0First glance at Akka 2.0
First glance at Akka 2.0
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQuery
 
Angular testing
Angular testingAngular testing
Angular testing
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and Karma
 
Akka knolx
Akka knolxAkka knolx
Akka knolx
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstitute
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and Karma
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmine
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
 
Akka 2.0 Reloaded
Akka 2.0 ReloadedAkka 2.0 Reloaded
Akka 2.0 Reloaded
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
Advanced akka features
Advanced akka featuresAdvanced akka features
Advanced akka features
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
 
Introduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users Group
 

Ähnlich wie Testing akka-actors

Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
Skills Matter
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
Yung-Lin Ho
 

Ähnlich wie Testing akka-actors (20)

Concurrency and scalability with akka
Concurrency and scalability  with akkaConcurrency and scalability  with akka
Concurrency and scalability with akka
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
Akka and futures
Akka and futuresAkka and futures
Akka and futures
 
Reactive programming with akka
Reactive programming with akkaReactive programming with akka
Reactive programming with akka
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Introduction to Akka
Introduction to AkkaIntroduction to Akka
Introduction to Akka
 
Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an Introduction
 
Building Massively Scalable application with Akka 2.0
Building Massively Scalable application with Akka 2.0Building Massively Scalable application with Akka 2.0
Building Massively Scalable application with Akka 2.0
 
Message-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applicationsMessage-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applications
 
Unit testing using jasmine in Javascript
Unit testing using jasmine in JavascriptUnit testing using jasmine in Javascript
Unit testing using jasmine in Javascript
 
Testing Ansible
Testing AnsibleTesting Ansible
Testing Ansible
 
jasmine
jasminejasmine
jasmine
 
Reactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.NetReactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.Net
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akka
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 

Mehr von Knoldus Inc.

Mehr von Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Kürzlich hochgeladen

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Kürzlich hochgeladen (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

Testing akka-actors

  • 1. Testing Akka ActorsTesting Akka Actors Piyush Mishra Software Consultant Knoldus Software LLP Piyush Mishra Software Consultant Knoldus Software LLP
  • 2. Topics CoveredTopics Covered Basics of Akka Settings in build.sbt Defining an of Akka Actor Creation of Akka Actor ActorRef Testing Akka Actors Integration testing using testkit Basics of Akka Settings in build.sbt Defining an of Akka Actor Creation of Akka Actor ActorRef Testing Akka Actors Integration testing using testkit
  • 3. What is AkkaWhat is Akka Akka is framework for writing event driving, concurrent, fault-tolerant and scalable application. a) It uses actor model to build concurrent, fault-tolerant and scalable application. b) Actors are the higher abstraction for concurrency and parallelism. c) They are very lightweight event-driven processes (approximately 2.7 million actors per GB RAM). d) Akka provides supervisor stategy to build fault tolerance Applications. Akka is framework for writing event driving, concurrent, fault-tolerant and scalable application. a) It uses actor model to build concurrent, fault-tolerant and scalable application. b) Actors are the higher abstraction for concurrency and parallelism. c) They are very lightweight event-driven processes (approximately 2.7 million actors per GB RAM). d) Akka provides supervisor stategy to build fault tolerance Applications.
  • 4. Settings in build.sbtSettings in build.sbt In order to test Akka actors we need to add following two dependencies in build.scala or build.sbt libraryDependencies ++= Seq( "com.typesafe.akka" % "akka-actor" % "2.0.5", "com.typesafe.akka" % "akka-testkit" % "2.0.5") In order to test Akka actors we need to add following two dependencies in build.scala or build.sbt libraryDependencies ++= Seq( "com.typesafe.akka" % "akka-actor" % "2.0.5", "com.typesafe.akka" % "akka-testkit" % "2.0.5")
  • 5. Defining an Akka actorDefining an Akka actor package com.Testing import akka.actor.Actor class SimpleActor extends Actor { def receive = { case msg: String => case _ => println("Got other than string") } } package com.Testing import akka.actor.Actor class SimpleActor extends Actor { def receive = { case msg: String => case _ => println("Got other than string") } }
  • 6. Creating an actorCreating an actor package com.Testing import akka.actor.ActorSystem import akka.actor.Props object CreateActor extends App { val system = ActorSystem("testing") val actor = system.actorOf(Props[SimpleActor]) actor ! "hello" } package com.Testing import akka.actor.ActorSystem import akka.actor.Props object CreateActor extends App { val system = ActorSystem("testing") val actor = system.actorOf(Props[SimpleActor]) actor ! "hello" }
  • 7. What is ActorRefWhat is ActorRef ActorRef is the Immutable and serializable handle to an actor which may or may not reside on the local host or inside the same ActorSystem . We can not call methods on actorRef. ActorRef is the Immutable and serializable handle to an actor which may or may not reside on the local host or inside the same ActorSystem . We can not call methods on actorRef.
  • 8. Testing with TestActorRefTesting with TestActorRef This special type of reference is designed specifically for test purposes and allows access to the actor in two ways: either by obtaining a reference to the underlying actor instance, or by invoking or querying the actor's behaviour (receive). This special type of reference is designed specifically for test purposes and allows access to the actor in two ways: either by obtaining a reference to the underlying actor instance, or by invoking or querying the actor's behaviour (receive).
  • 9. Obtaining a Reference to an ActorObtaining a Reference to an Actor import akka.testkit.TestActorRef val actorRef = TestActorRef[MyActor] val actor = actorRef.underlyingActor import akka.testkit.TestActorRef val actorRef = TestActorRef[MyActor] val actor = actorRef.underlyingActor
  • 10. Testing the Actor's BehaviorTesting the Actor's Behavior implicit val timeout = Timeout(5 seconds) implicit val system = ActorSystem("Unit") val actorRef = TestActorRef(new SimpleActor) val result = Await.result((actorRef ? 42), 5 seconds).asInstanceOf[Int] result must be(42) implicit val timeout = Timeout(5 seconds) implicit val system = ActorSystem("Unit") val actorRef = TestActorRef(new SimpleActor) val result = Await.result((actorRef ? 42), 5 seconds).asInstanceOf[Int] result must be(42)
  • 11. Integration test with TestkitIntegration test with Testkit Testkit is used for integration testing of an actor. This toolkit provider a ImplicitSender which is actually a test actor which dispatches messages to actors under test. Continued Testkit is used for integration testing of an actor. This toolkit provider a ImplicitSender which is actually a test actor which dispatches messages to actors under test. Continued
  • 12. Integration test with TestkitIntegration test with Testkit class MySpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with WordSpec with MustMatchers with BeforeAndAfterAll { def this() = this(ActorSystem("MySpec")) import MySpec._ override def afterAll { system.shutdown() } "An Echo actor" must { "send back messages unchanged" in { val echo = system.actorOf(Props[EchoActor]) echo ! "hello world" expectMsg("hello world") } class MySpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with WordSpec with MustMatchers with BeforeAndAfterAll { def this() = this(ActorSystem("MySpec")) import MySpec._ override def afterAll { system.shutdown() } "An Echo actor" must { "send back messages unchanged" in { val echo = system.actorOf(Props[EchoActor]) echo ! "hello world" expectMsg("hello world") }
  • 13. Timing AssertionsTiming Assertions Timing: certain events must not happen immediately (like a timer), others need to happen before a deadline. The block given to within must complete after a Duration which is between min and max, where the former defaults to zero. The deadline calculated by adding the max parameter to the block's start time is implicitly available within the block to all examination methods Timing: certain events must not happen immediately (like a timer), others need to happen before a deadline. The block given to within must complete after a Duration which is between min and max, where the former defaults to zero. The deadline calculated by adding the max parameter to the block's start time is implicitly available within the block to all examination methods
  • 14. Timing AssertionsTiming Assertions class Timing(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with MustMatchers with WordSpec { def this() = this(ActorSystem("MySpec")) import MySpec._ "An simple actor" must { "send reply within 2 seconds" in { val worker = system.actorOf(Props[SimpleActor]) within(200 millis) { worker ! 4 expectMsg(4) expectNoMsg // will block for the rest of the 200ms Thread.sleep(300) // will NOT make this block fail } } } } class Timing(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with MustMatchers with WordSpec { def this() = this(ActorSystem("MySpec")) import MySpec._ "An simple actor" must { "send reply within 2 seconds" in { val worker = system.actorOf(Props[SimpleActor]) within(200 millis) { worker ! 4 expectMsg(4) expectNoMsg // will block for the rest of the 200ms Thread.sleep(300) // will NOT make this block fail } } } }
  • 15. Using ProbesUsing Probes When the actors under test are supposed to send various messages to different destinations. approach is to use it for creation of simple probe actors to be inserted in the message flows. To make this more powerful and convenient, there is a concrete implementation called TestProbe. The functionality is best explained using a small example When the actors under test are supposed to send various messages to different destinations. approach is to use it for creation of simple probe actors to be inserted in the message flows. To make this more powerful and convenient, there is a concrete implementation called TestProbe. The functionality is best explained using a small example
  • 16. Using ProbesUsing Probes class Probe(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with WordSpec with MustMatchers with BeforeAndAfterAll { def this() = this(ActorSystem("MySpec")) import MySpec._ override def afterAll { system.shutdown() } "An DoubleEcho actor" must { "send reply both probes" in { val probe1 = TestProbe() val probe2 = TestProbe() val actor = system.actorOf(Props[MyDoubleEcho]) actor ! (probe1.ref, probe2.ref) actor ! "hello" probe1.expectMsg(500 millis, "hello") probe2.expectMsg(500 millis, "hello") } } } class Probe(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with WordSpec with MustMatchers with BeforeAndAfterAll { def this() = this(ActorSystem("MySpec")) import MySpec._ override def afterAll { system.shutdown() } "An DoubleEcho actor" must { "send reply both probes" in { val probe1 = TestProbe() val probe2 = TestProbe() val actor = system.actorOf(Props[MyDoubleEcho]) actor ! (probe1.ref, probe2.ref) actor ! "hello" probe1.expectMsg(500 millis, "hello") probe2.expectMsg(500 millis, "hello") } } }