SlideShare a Scribd company logo
1 of 59
Download to read offline
Reactive Amsterdam meetup 12.07.2016
Mike Kotsur

@sotomajor_ua
Actor testing patterns
with TestKit
• Testing
• Testing Akka applications
• Better testing Akka applications
• Testing Akka applications with less problems
Agenda
TDD
A provocative talk and blog
posts has led to a conversation
where we aim to understand
each others' views and
experiences.
http://martinfowler.com/articles/is-tdd-dead/
Is TDD dead?
M. Fowler
K. Beck
David Heinemeier
Hansson
Programmers at work maintaining a Ruby on Rails testless application
Eero Järnefelt, Oil on canvas, 1893
A test
An async test
An async test
• Retry the assertion many times;
• The worker tells when the work is done.
2 conceptual solutions
• Retry the assertion many times;
• The worker tells when the work is done.
2 conceptual solutions
questions
How many times?
How long to wait?
• Not just actors and messages!
• Willing to help you with the test kit.
So, what about Akka?
object IncrementorActorMessages {

case class Inc(i: Int)

}



class IncrementorActor extends Actor {

var sum: Int = 0



override def receive: Receive = {

case Inc(i) => sum = sum + i

}

}
// TODO: test this
class IncrementorActorTest

extends TestKit(ActorSystem("test-system")) {





// it(“should …”) { … }





}
// We need an actor system
it("should have sum = 0 by default") {



val actorRef = TestActorRef[IncrementorActor]

actorRef.underlyingActor.sum shouldEqual 0



}
// Uses the same thread
Has a real type!
it("should increment on new messages1") {



val actorRef = TestActorRef[IncrementorActor]



actorRef ! Inc(2)

actorRef.underlyingActor.sum shouldEqual 2



actorRef.underlyingActor.receive(Inc(3))

actorRef.underlyingActor.sum shouldEqual 5



}


it("should increment on new messages2") {



val actorRef = TestActorRef[IncrementorActor]



actorRef ! Inc(2)

actorRef.underlyingActor.sum shouldEqual 2



actorRef.underlyingActor.receive(Inc(3))

actorRef.underlyingActor.sum shouldEqual 5



}
// “Sending” messages
Style 1
Style 2
class LazyIncrementorActor extends Actor {

var sum: Int = 0



override def receive: Receive = {

case Inc(i) =>

Future {

Thread.sleep(100)

sum = sum + i

}

}



}
object IncrementorActorMessages {
case class Inc(i: Int)
case object Result
}
class IncrementorActor extends Actor {
var sum: Int = 0
override def receive: Receive = {
case Inc(i) => sum = sum + i
case Result => sender() ! sum
}
}
New message
// ... with ImplicitSender
it("should have sum = 0 by default") {
val actorRef = system
.actorOf(Props(classOf[IncrementorActor]))
actorRef ! Result
expectMsg(0)
}
TestKit trait
it("should increment on new messages") {
val actorRef = system
.actorOf(Props(classOf[IncrementorActor]))
actorRef ! Inc(2)
actorRef ! Result
expectMsg(2)
actorRef ! Inc(3)
actorRef ! Result
expectMsg(5)
}
TestKit
def expectMsg[T](d: Duration, msg: T): T
def expectMsgPF[T](d: Duration)
(pf:PartialFunction[Any, T]): T
def expectMsgClass[T](d: Duration, c: Class[T]): T
def expectNoMsg(d: Duration) // blocks
// expectMsg*
def receiveN(n: Int, d: Duration): Seq[AnyRef]
def receiveWhile[T](max: Duration, idle: Duration, n: Int)
(pf: PartialFunction[Any, T]): Seq[T]
def fishForMessage(max: Duration, hint: String)
(pf: PartialFunction[Any, Boolean]): Any
// fishing*
def awaitCond(p: => Boolean, max: Duration, interval:
Duration)
def awaitAssert(a: => Any, max: Duration, interval: Duration)
// from ScalaTest
def eventually[T](fun: => T)
(implicit config: PatienceConfig): T
// await*
def ignoreMsg(pf: PartialFunction[AnyRef, Boolean])
def ignoreNoMsg()
// ignore*
val probe = TestProbe()
probe watch target
target ! PoisonPill
probe.expectTerminated(target)
// death watch
Somewhere in the app code
• context.actorOf()
• context.parent
• context.child(name)
Dependency injection
• Use props;
• Use childMaker: ActorRefFactory =>
ActorRef;
• Use a fabricated parent.
Dependency Injection
class MyActor extends Actor with ActorLogging {
override def receive: Receive = {
case DoSideEffect =>
log.info("Hello World!")
}
}
// event filter
// akka.loggers = ["akka.testkit.TestEventListener"]
EventFilter.info(
message = "Hello World!”, occurrences = 1
).intercept {
myActor ! DoSomething
}
// event filter
class MyActor extends Actor with ActorLogging {
override def supervisorStrategy: Unit =
OneForOneStrategy() {
case _: FatalException =>
SupervisorStrategy.Escalate
case _: ShitHappensException =>
SupervisorStrategy.Restart
}
}
// supervision
// unit-test style
val actorRef = TestActorRef[MyActor](MyActor.props())
val pf = actorRef.underlyingActor
.supervisorStrategy.decider
pf(new FatalException()) should be (Escalate)
pf(new ShitHappensException()) should be (Restart)
// supervision
// coding time
// better tests
flaky /ˈfleɪki/ adjective,
informal
(of a device or
software) prone to
break down; unreliable.
class MyActorTest
extends TestKit(ActorSystem("test-system"))
with FunSpecLike {
override protected def afterAll(): Unit = {
super.afterAll()
system.shutdown()
system.awaitTermination()
}
}
// shutting down the actor system
trait AkkaTestBase extends BeforeAndAfterAll
with FunSpecLike { this: TestKit with Suite =>
override protected def afterAll() {
super.afterAll()
system.shutdown()
system.awaitTermination()
}
}
// shutting down the actor system
akka.test.single-expect-default = 3 seconds
akka.test.timefactor = 10
// timeouts
import scala.concurrent.duration._
import akka.testkit._
10.milliseconds.dilated
class Settings(...) extends Extension {
object Jdbc {
val Driver = config.getString("app.jdbc.driver")
val Url = config.getString("app.jdbc.url")
}
}
// settings extension
// test
val config = ConfigFactory.parseString("""
app.jdbc.driver = "org.h2.Driver"
app.jdbc.url = "jdbc:h2:mem:repository"
""")
val system = ActorSystem("testsystem", config)
// app
class MyActor extends Actor {
val settings = Settings(context.system)
val connection = client.connect(
settings.Jdbc.Driver,
settings.Jdbc.Url
)
}
// settings extension
case class Identify(messageId: Any)
case class ActorIdentity(
correlationId: Any,
ref: Option[ActorRef]
)
// dynamic actors
// Beware of unique name lifecycles and scopes…
// Prefer checking messages over checking side-effects.
// Single responsibility principle.
// Run your tests on slow VM and different OS.
// Extract *all* timeouts into conf files. So that you can easily
override them
-Dakka.test.someImportantProperty=3000
// Don’t hesitate to rewrite a test, or the code.
// Don’t trust assertion errors, check logs.
// Base your decisions on historical data.
// QA?

More Related Content

What's hot

Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
Harry Potter
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockito
Mathieu Carbou
 

What's hot (20)

So I used Erlang... is my system as scalable as they say it'd be?
So I used Erlang... is my system as scalable as they say it'd be?So I used Erlang... is my system as scalable as they say it'd be?
So I used Erlang... is my system as scalable as they say it'd be?
 
JUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit TestsJUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit Tests
 
Implementing a decorator for thread synchronisation.
Implementing a decorator for thread synchronisation.Implementing a decorator for thread synchronisation.
Implementing a decorator for thread synchronisation.
 
unittest in 5 minutes
unittest in 5 minutesunittest in 5 minutes
unittest in 5 minutes
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Pyunit
PyunitPyunit
Pyunit
 
Scala test
Scala testScala test
Scala test
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasmine
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockito
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
C++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkC++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing Framework
 

Viewers also liked

РИФ 2016, Брендинг регионов/территорий в социальных сетях посредством продвиж...
РИФ 2016, Брендинг регионов/территорий в социальных сетях посредством продвиж...РИФ 2016, Брендинг регионов/территорий в социальных сетях посредством продвиж...
РИФ 2016, Брендинг регионов/территорий в социальных сетях посредством продвиж...
Тарасов Константин
 
Переходя все границы - 2, UATD, Одесса, 2012
Переходя все границы - 2, UATD, Одесса, 2012Переходя все границы - 2, UATD, Одесса, 2012
Переходя все границы - 2, UATD, Одесса, 2012
Alexei Barantsev
 
דברים שכדי לעולם העסקי ללמוד הטור דה פראנס ודבר אחד שלא חומר לאתר
דברים שכדי לעולם העסקי ללמוד הטור דה פראנס ודבר אחד שלא   חומר לאתרדברים שכדי לעולם העסקי ללמוד הטור דה פראנס ודבר אחד שלא   חומר לאתר
דברים שכדי לעולם העסקי ללמוד הטור דה פראנס ודבר אחד שלא חומר לאתר
yossi koren
 
152 shopping strategies
152 shopping   strategies152 shopping   strategies
152 shopping strategies
hilad
 
Zambia Capital Ask - draft
Zambia Capital Ask - draftZambia Capital Ask - draft
Zambia Capital Ask - draft
Andy Lehman
 
Polska – moja ojczyzna
Polska – moja ojczyznaPolska – moja ojczyzna
Polska – moja ojczyzna
teq
 
РИФ 2016, Программатик-симбиоз площадки и рекламодателя: как получить максиму...
РИФ 2016, Программатик-симбиоз площадки и рекламодателя: как получить максиму...РИФ 2016, Программатик-симбиоз площадки и рекламодателя: как получить максиму...
РИФ 2016, Программатик-симбиоз площадки и рекламодателя: как получить максиму...
Тарасов Константин
 

Viewers also liked (20)

РИФ 2016, Сколько можно говорить о мобильных?
РИФ 2016, Сколько можно говорить о мобильных?РИФ 2016, Сколько можно говорить о мобильных?
РИФ 2016, Сколько можно говорить о мобильных?
 
РИФ 2016, Привлечение и анализ трафика в мобильниках
РИФ 2016, Привлечение и анализ трафика в мобильникахРИФ 2016, Привлечение и анализ трафика в мобильниках
РИФ 2016, Привлечение и анализ трафика в мобильниках
 
РИФ 2016, Панавто ДЦ Mercedes-Benz: что делать со сквозной аналитикой или зач...
РИФ 2016, Панавто ДЦ Mercedes-Benz: что делать со сквозной аналитикой или зач...РИФ 2016, Панавто ДЦ Mercedes-Benz: что делать со сквозной аналитикой или зач...
РИФ 2016, Панавто ДЦ Mercedes-Benz: что делать со сквозной аналитикой или зач...
 
РИФ 2016, Брендинг регионов/территорий в социальных сетях посредством продвиж...
РИФ 2016, Брендинг регионов/территорий в социальных сетях посредством продвиж...РИФ 2016, Брендинг регионов/территорий в социальных сетях посредством продвиж...
РИФ 2016, Брендинг регионов/территорий в социальных сетях посредством продвиж...
 
РИФ 2016, Инфографика как инструмент контент-маркетинга
РИФ 2016, Инфографика как инструмент контент-маркетингаРИФ 2016, Инфографика как инструмент контент-маркетинга
РИФ 2016, Инфографика как инструмент контент-маркетинга
 
Переходя все границы - 2, UATD, Одесса, 2012
Переходя все границы - 2, UATD, Одесса, 2012Переходя все границы - 2, UATD, Одесса, 2012
Переходя все границы - 2, UATD, Одесса, 2012
 
דברים שכדי לעולם העסקי ללמוד הטור דה פראנס ודבר אחד שלא חומר לאתר
דברים שכדי לעולם העסקי ללמוד הטור דה פראנס ודבר אחד שלא   חומר לאתרדברים שכדי לעולם העסקי ללמוד הטור דה פראנס ודבר אחד שלא   חומר לאתר
דברים שכדי לעולם העסקי ללמוד הטור דה פראנס ודבר אחד שלא חומר לאתר
 
Affinity Groups Reader
Affinity Groups ReaderAffinity Groups Reader
Affinity Groups Reader
 
152 shopping strategies
152 shopping   strategies152 shopping   strategies
152 shopping strategies
 
Zambia Capital Ask - draft
Zambia Capital Ask - draftZambia Capital Ask - draft
Zambia Capital Ask - draft
 
Noruega En Invierno
Noruega En InviernoNoruega En Invierno
Noruega En Invierno
 
РИФ 2016, Как мы создавали amoCRM, в рамках агенства
РИФ 2016, Как мы создавали amoCRM, в рамках агенстваРИФ 2016, Как мы создавали amoCRM, в рамках агенства
РИФ 2016, Как мы создавали amoCRM, в рамках агенства
 
РИФ 2016, Оптимизация СРА в дорогих сегментах
РИФ 2016, Оптимизация СРА в дорогих сегментахРИФ 2016, Оптимизация СРА в дорогих сегментах
РИФ 2016, Оптимизация СРА в дорогих сегментах
 
Polska – moja ojczyzna
Polska – moja ojczyznaPolska – moja ojczyzna
Polska – moja ojczyzna
 
РИФ 2016 Профессиональные стандарты и сертификация UX- и юзабилити-специалист...
РИФ 2016 Профессиональные стандарты и сертификация UX- и юзабилити-специалист...РИФ 2016 Профессиональные стандарты и сертификация UX- и юзабилити-специалист...
РИФ 2016 Профессиональные стандарты и сертификация UX- и юзабилити-специалист...
 
РИФ 2016, Сквозная аналитика с автоматизацией бизнес-процессов.
РИФ 2016, Сквозная аналитика с автоматизацией бизнес-процессов.РИФ 2016, Сквозная аналитика с автоматизацией бизнес-процессов.
РИФ 2016, Сквозная аналитика с автоматизацией бизнес-процессов.
 
РИФ 2016, Est-a-tet: Google AdWords, Яндекс.Директ, ремаркетинг
РИФ 2016, Est-a-tet: Google AdWords, Яндекс.Директ, ремаркетингРИФ 2016, Est-a-tet: Google AdWords, Яндекс.Директ, ремаркетинг
РИФ 2016, Est-a-tet: Google AdWords, Яндекс.Директ, ремаркетинг
 
РИФ 2016, Программатик-симбиоз площадки и рекламодателя: как получить максиму...
РИФ 2016, Программатик-симбиоз площадки и рекламодателя: как получить максиму...РИФ 2016, Программатик-симбиоз площадки и рекламодателя: как получить максиму...
РИФ 2016, Программатик-симбиоз площадки и рекламодателя: как получить максиму...
 
MS2 Max and Min Points
MS2 Max and Min PointsMS2 Max and Min Points
MS2 Max and Min Points
 
РИФ 2016, Внедрение контроля качества в большом web-проекте на примере Badoo
РИФ 2016, Внедрение контроля качества в большом web-проекте на примере BadooРИФ 2016, Внедрение контроля качества в большом web-проекте на примере Badoo
РИФ 2016, Внедрение контроля качества в большом web-проекте на примере Badoo
 

Similar to Akka Testkit Patterns

Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
Skills Matter
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Mario Fusco
 

Similar to Akka Testkit Patterns (20)

Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
Testing akka-actors
Testing akka-actorsTesting akka-actors
Testing akka-actors
 
Akka 2.0 Reloaded
Akka 2.0 ReloadedAkka 2.0 Reloaded
Akka 2.0 Reloaded
 
Akka knolx
Akka knolxAkka knolx
Akka knolx
 
Networks and types - the future of Akka
Networks and types - the future of AkkaNetworks and types - the future of Akka
Networks and types - the future of Akka
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akka
 
Improve unit tests with Mutants!
Improve unit tests with Mutants!Improve unit tests with Mutants!
Improve unit tests with Mutants!
 
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
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Scale up your thinking
Scale up your thinkingScale up your thinking
Scale up your thinking
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Akka
AkkaAkka
Akka
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
 
Advances in Unit Testing: Theory and Practice
Advances in Unit Testing: Theory and PracticeAdvances in Unit Testing: Theory and Practice
Advances in Unit Testing: Theory and Practice
 
Mutation testing Bucharest Tech Week
Mutation testing Bucharest Tech WeekMutation testing Bucharest Tech Week
Mutation testing Bucharest Tech Week
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 

Recently uploaded

Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
dharasingh5698
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 

Akka Testkit Patterns

  • 1. Reactive Amsterdam meetup 12.07.2016 Mike Kotsur
 @sotomajor_ua Actor testing patterns with TestKit
  • 2. • Testing • Testing Akka applications • Better testing Akka applications • Testing Akka applications with less problems Agenda
  • 3. TDD
  • 4. A provocative talk and blog posts has led to a conversation where we aim to understand each others' views and experiences. http://martinfowler.com/articles/is-tdd-dead/ Is TDD dead? M. Fowler K. Beck David Heinemeier Hansson
  • 5. Programmers at work maintaining a Ruby on Rails testless application Eero Järnefelt, Oil on canvas, 1893
  • 9. • Retry the assertion many times; • The worker tells when the work is done. 2 conceptual solutions
  • 10. • Retry the assertion many times; • The worker tells when the work is done. 2 conceptual solutions questions How many times? How long to wait?
  • 11. • Not just actors and messages! • Willing to help you with the test kit. So, what about Akka?
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18. object IncrementorActorMessages {
 case class Inc(i: Int)
 }
 
 class IncrementorActor extends Actor {
 var sum: Int = 0
 
 override def receive: Receive = {
 case Inc(i) => sum = sum + i
 }
 } // TODO: test this
  • 19. class IncrementorActorTest
 extends TestKit(ActorSystem("test-system")) {
 
 
 // it(“should …”) { … }
 
 
 } // We need an actor system
  • 20. it("should have sum = 0 by default") {
 
 val actorRef = TestActorRef[IncrementorActor]
 actorRef.underlyingActor.sum shouldEqual 0
 
 } // Uses the same thread Has a real type!
  • 21. it("should increment on new messages1") {
 
 val actorRef = TestActorRef[IncrementorActor]
 
 actorRef ! Inc(2)
 actorRef.underlyingActor.sum shouldEqual 2
 
 actorRef.underlyingActor.receive(Inc(3))
 actorRef.underlyingActor.sum shouldEqual 5
 
 } 
 it("should increment on new messages2") {
 
 val actorRef = TestActorRef[IncrementorActor]
 
 actorRef ! Inc(2)
 actorRef.underlyingActor.sum shouldEqual 2
 
 actorRef.underlyingActor.receive(Inc(3))
 actorRef.underlyingActor.sum shouldEqual 5
 
 } // “Sending” messages Style 1 Style 2
  • 22. class LazyIncrementorActor extends Actor {
 var sum: Int = 0
 
 override def receive: Receive = {
 case Inc(i) =>
 Future {
 Thread.sleep(100)
 sum = sum + i
 }
 }
 
 }
  • 23.
  • 24.
  • 25.
  • 26.
  • 27. object IncrementorActorMessages { case class Inc(i: Int) case object Result } class IncrementorActor extends Actor { var sum: Int = 0 override def receive: Receive = { case Inc(i) => sum = sum + i case Result => sender() ! sum } } New message
  • 28. // ... with ImplicitSender it("should have sum = 0 by default") { val actorRef = system .actorOf(Props(classOf[IncrementorActor])) actorRef ! Result expectMsg(0) } TestKit trait
  • 29. it("should increment on new messages") { val actorRef = system .actorOf(Props(classOf[IncrementorActor])) actorRef ! Inc(2) actorRef ! Result expectMsg(2) actorRef ! Inc(3) actorRef ! Result expectMsg(5) }
  • 31. def expectMsg[T](d: Duration, msg: T): T def expectMsgPF[T](d: Duration) (pf:PartialFunction[Any, T]): T def expectMsgClass[T](d: Duration, c: Class[T]): T def expectNoMsg(d: Duration) // blocks // expectMsg*
  • 32. def receiveN(n: Int, d: Duration): Seq[AnyRef] def receiveWhile[T](max: Duration, idle: Duration, n: Int) (pf: PartialFunction[Any, T]): Seq[T] def fishForMessage(max: Duration, hint: String) (pf: PartialFunction[Any, Boolean]): Any // fishing*
  • 33. def awaitCond(p: => Boolean, max: Duration, interval: Duration) def awaitAssert(a: => Any, max: Duration, interval: Duration) // from ScalaTest def eventually[T](fun: => T) (implicit config: PatienceConfig): T // await*
  • 34. def ignoreMsg(pf: PartialFunction[AnyRef, Boolean]) def ignoreNoMsg() // ignore*
  • 35. val probe = TestProbe() probe watch target target ! PoisonPill probe.expectTerminated(target) // death watch Somewhere in the app code
  • 36. • context.actorOf() • context.parent • context.child(name) Dependency injection
  • 37. • Use props; • Use childMaker: ActorRefFactory => ActorRef; • Use a fabricated parent. Dependency Injection
  • 38. class MyActor extends Actor with ActorLogging { override def receive: Receive = { case DoSideEffect => log.info("Hello World!") } } // event filter
  • 39. // akka.loggers = ["akka.testkit.TestEventListener"] EventFilter.info( message = "Hello World!”, occurrences = 1 ).intercept { myActor ! DoSomething } // event filter
  • 40. class MyActor extends Actor with ActorLogging { override def supervisorStrategy: Unit = OneForOneStrategy() { case _: FatalException => SupervisorStrategy.Escalate case _: ShitHappensException => SupervisorStrategy.Restart } } // supervision
  • 41. // unit-test style val actorRef = TestActorRef[MyActor](MyActor.props()) val pf = actorRef.underlyingActor .supervisorStrategy.decider pf(new FatalException()) should be (Escalate) pf(new ShitHappensException()) should be (Restart) // supervision
  • 44. flaky /ˈfleɪki/ adjective, informal (of a device or software) prone to break down; unreliable.
  • 45. class MyActorTest extends TestKit(ActorSystem("test-system")) with FunSpecLike { override protected def afterAll(): Unit = { super.afterAll() system.shutdown() system.awaitTermination() } } // shutting down the actor system
  • 46. trait AkkaTestBase extends BeforeAndAfterAll with FunSpecLike { this: TestKit with Suite => override protected def afterAll() { super.afterAll() system.shutdown() system.awaitTermination() } } // shutting down the actor system
  • 47. akka.test.single-expect-default = 3 seconds akka.test.timefactor = 10 // timeouts import scala.concurrent.duration._ import akka.testkit._ 10.milliseconds.dilated
  • 48. class Settings(...) extends Extension { object Jdbc { val Driver = config.getString("app.jdbc.driver") val Url = config.getString("app.jdbc.url") } } // settings extension
  • 49. // test val config = ConfigFactory.parseString(""" app.jdbc.driver = "org.h2.Driver" app.jdbc.url = "jdbc:h2:mem:repository" """) val system = ActorSystem("testsystem", config) // app class MyActor extends Actor { val settings = Settings(context.system) val connection = client.connect( settings.Jdbc.Driver, settings.Jdbc.Url ) } // settings extension
  • 50. case class Identify(messageId: Any) case class ActorIdentity( correlationId: Any, ref: Option[ActorRef] ) // dynamic actors
  • 51. // Beware of unique name lifecycles and scopes…
  • 52. // Prefer checking messages over checking side-effects.
  • 54. // Run your tests on slow VM and different OS.
  • 55. // Extract *all* timeouts into conf files. So that you can easily override them -Dakka.test.someImportantProperty=3000
  • 56. // Don’t hesitate to rewrite a test, or the code.
  • 57. // Don’t trust assertion errors, check logs.
  • 58. // Base your decisions on historical data.