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

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?Laura M. Castro
 
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 TestsJohn Ferguson Smart Limited
 
Implementing a decorator for thread synchronisation.
Implementing a decorator for thread synchronisation.Implementing a decorator for thread synchronisation.
Implementing a decorator for thread synchronisation.Graham Dumpleton
 
unittest in 5 minutes
unittest in 5 minutesunittest in 5 minutes
unittest in 5 minutesRay Toal
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsFITC
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With PythonSiddhi
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSJim Lynch
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 
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 Jasminefoxp2code
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With SpockIT Weekend
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockitoMathieu Carbou
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSKnoldus Inc.
 
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 TutorialAnup Singh
 
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 FrameworkHumberto Marchezi
 

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, Сколько можно говорить о мобильных?Тарасов Константин
 
РИФ 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, Одесса, 2012Alexei Barantsev
 
דברים שכדי לעולם העסקי ללמוד הטור דה פראנס ודבר אחד שלא חומר לאתר
דברים שכדי לעולם העסקי ללמוד הטור דה פראנס ודבר אחד שלא   חומר לאתרדברים שכדי לעולם העסקי ללמוד הטור דה פראנס ודבר אחד שלא   חומר לאתר
דברים שכדי לעולם העסקי ללמוד הטור דה פראנס ודבר אחד שלא חומר לאתרyossi koren
 
152 shopping strategies
152 shopping   strategies152 shopping   strategies
152 shopping strategieshilad
 
Zambia Capital Ask - draft
Zambia Capital Ask - draftZambia Capital Ask - draft
Zambia Capital Ask - draftAndy Lehman
 
РИФ 2016, Как мы создавали amoCRM, в рамках агенства
РИФ 2016, Как мы создавали amoCRM, в рамках агенстваРИФ 2016, Как мы создавали amoCRM, в рамках агенства
РИФ 2016, Как мы создавали amoCRM, в рамках агенстваТарасов Константин
 
РИФ 2016, Оптимизация СРА в дорогих сегментах
РИФ 2016, Оптимизация СРА в дорогих сегментахРИФ 2016, Оптимизация СРА в дорогих сегментах
РИФ 2016, Оптимизация СРА в дорогих сегментахТарасов Константин
 
Polska – moja ojczyzna
Polska – moja ojczyznaPolska – moja ojczyzna
Polska – moja ojczyznateq
 
РИФ 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, Программатик-симбиоз площадки и рекламодателя: как получить максиму...Тарасов Константин
 
РИФ 2016, Внедрение контроля качества в большом web-проекте на примере Badoo
РИФ 2016, Внедрение контроля качества в большом web-проекте на примере BadooРИФ 2016, Внедрение контроля качества в большом web-проекте на примере Badoo
РИФ 2016, Внедрение контроля качества в большом web-проекте на примере BadooТарасов Константин
 

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 Testing Akka applications with TestKit

Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_groupSkills Matter
 
Testing akka-actors
Testing akka-actorsTesting akka-actors
Testing akka-actorsKnoldus Inc.
 
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 AkkaJohan Andrén
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaAD_
 
Improve unit tests with Mutants!
Improve unit tests with Mutants!Improve unit tests with Mutants!
Improve unit tests with Mutants!Paco van Beckhoven
 
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 applicationsAndrii Lashchenko
 
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 DevelopmentAll Things Open
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 
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 TestsTomek Kaczanowski
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytestHector Canto
 
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 & STMMario Fusco
 
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 JSMichael Haberman
 
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 PracticeTao Xie
 
Mutation testing Bucharest Tech Week
Mutation testing Bucharest Tech WeekMutation testing Bucharest Tech Week
Mutation testing Bucharest Tech WeekPaco van Beckhoven
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matterSkills Matter
 

Similar to Testing Akka applications with TestKit (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

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
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 Performancesivaprakash250
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 

Recently uploaded (20)

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
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
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 

Testing Akka applications with TestKit

  • 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.