SlideShare a Scribd company logo
1 of 35
Testing in Scala
Concepts: Types of Tests
Technology
Business
GlobalLocal
Unit Integration
Functional
Acceptance
Unit Tests
• Check very specific functionality of your code
• Assumes everything else works (mocking)
• Test one specific/technical thing
• e.g. test your Hadoop job locally, given money in DKK, currency
conversion to EUR is called once
Integration Tests
• Check that all components work together
• Includes real components, databases, files, etc.
• Test the connectivity of components
• e.g. run a job on a development Hadoop cluster, given sample data
expected output is written
Functional Tests
• Test your product against the functionality you developed
• Use real components, real data
• E.g. run job on a live cluster, given a days worth of data the output is
correct (as expected according to specification)
Acceptance Tests
• Final tests performed by your client before “accepting the product”
• Real components, real data, output is correct, performance is
acceptable, client is happy
Concepts: Testing Styles
• TDD: Test Driven Development
• BDD: Behavior Driven Development
Test Driven Development
• Write an interface (trait) for the behavior
• Write an empty implementation
• Write your unit tests
• Make the code compile and tests fail
• Correct the implementation
• Make the tests pass !
Behavior Driven Development
• Same idea, just write more functional tests (define behavior)
Testing in Scala
• For every class in src/main/scala write a test class in src/test/scala
• Test classes ~ Test suites
• Methods ~ Tests
• Run the suit and see the output
Testing Libraries/Frameworks
• Java: JUnit, TestNG (can be used with scala)
• Scala: ScalaTest, Specs2
• Mocking: ScalaMock, EasyMock, JMock, Mockito
• Property Testing: ScalaCheck
• UI Testing: Selenium
• Very similar to Specs2, maybe more flexible, mainly choice of taste
• Integrates with sbt, IntelliJ
• Integrates with Mockito, ScalaCheck
libraryDependencies += "org.scalatest" %% "scalatest" % "2.2.1" % "test"
Using ScalaTest
import org.scalatest.FunSuite
class SetSuite extends FunSuite {
test("An empty Set should have size 0") {
assert(Set.empty.size == 0)
}
test("Invoking head on an empty Set should produce NoSuchElementException") {
intercept[NoSuchElementException] {
Set.empty.head
}
}
}
Style Traits
• ScalaTest allows you to mix in a testing style you like:
• FunSuite
• FlatSpec
• FunSpec
• WordSpec
• PropSpec
• etc.
• http://www.scalatest.org/user_guide/selecting_a_style
FunSuite
FlatSpec
WordSpec
FeatureSpec
Testing Styles
• ScalaTest recommends having an abstract class with the specs and
other traits you like
package com.mycompany.myproject
import org.scalatest._
abstract class UnitSpec extends FlatSpec with Matchers with OptionValues with Inside with Inspectors
package com.mycompany.myproject
import org.scalatest._
class MySpec extends UnitSpec {
// Your tests here
}
Fixtures
• Your tests may need some setting up and tearing down
• ScalaTest has many ways of doing this
• http://www.scalatest.org/user_guide/sharing_fixtures
Matchers
• ScalaTest has lots of syntactic sugar to express your desires
result should equal (3)
result should have size 10
string should fullyMatch regex """(-)?(d+)(.d*)?"""
result1 should not be an [Orangutan]
sevenDotOh should equal (6.9 +- 0.2)
"howdy" should contain oneOf ('a', 'b', 'c', 'd')
(Array("Doe", "Ray", "Me") should contain oneOf ("X", "RAY", "BEAM")) (after being lowerCased)
List(0, 1, 2, 2, 99, 3, 3, 3, 5) should contain inOrder (1, 2, 3)
map should (contain key ("two") and not contain value (7))
This is Scala Code !!
Mocking
• You should always code against interfaces (traits)
• If you do, testing is easier, since you can mock your dependencies!
val m = mock[Turtle]
m.expects.forward(10.0) twice
m1 returns 42
m2 expects ("this", "that") returning "the other"
Property Based Testing
• New and exciting way of testing your code!
• Instead of examples, you specify properties (higher order testing!)
• E.g. when you concatenate two lists, new lengths is sum of lengths
• ScalaCheck then generates random inputs and runs many tests
• This can catch MANY corner cases you never expect!
ScalaCheck
import org.scalacheck.Gen
val propConcatLists = forAll { (l1: List[Int], l2: List[Int]) =>
l1.size + l2.size == (l1 ::: l2).size
}
+ OK, passed 100 tests.
val propSqrt = forAll { (n: Int) => scala.math.sqrt(n*n) == n }
! Falsified after 1 passed tests:
> -1
ScalaCheck: Generators
val genLeaf = value(Leaf)
val genNode = for {
v <- arbitrary[Int]
left <- genTree
right <- genTree
} yield Node(left, right, v)
def genTree: Gen[Tree] = oneOf(genLeaf, genNode)
Option[Tree] = Some(Node(Leaf,Node(Node(Node(Node(Node(Node(Leaf,Leaf,-
71),Node(Leaf,Leaf,-49),17),Leaf,-20),Leaf,-7),Node(Node(Leaf,Leaf,26),Leaf,-
3),49),Leaf,84),-29))
is
AWESOME !!
Scoverage
• Produces test coverage reports
• Measures how many statements are tested
• Only works with Scala 2.11
Testing Scalding Jobs
HOMEWORK: use ScalaTest instead of Specs2
DEMO TIME
Slava takes the stage
Testing in Scala by Adform research

More Related Content

What's hot

"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров
Fwdays
 
Akka in Practice: Designing Actor-based Applications
Akka in Practice: Designing Actor-based ApplicationsAkka in Practice: Designing Actor-based Applications
Akka in Practice: Designing Actor-based Applications
NLJUG
 
Real-time search in Drupal. Meet Elasticsearch
Real-time search in Drupal. Meet ElasticsearchReal-time search in Drupal. Meet Elasticsearch
Real-time search in Drupal. Meet Elasticsearch
Alexei Gorobets
 

What's hot (19)

Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentation
 
Full Stack Scala
Full Stack ScalaFull Stack Scala
Full Stack Scala
 
Scala.js - yet another what..?
Scala.js - yet another what..?Scala.js - yet another what..?
Scala.js - yet another what..?
 
"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров
 
Curator intro
Curator introCurator intro
Curator intro
 
First glance at Akka 2.0
First glance at Akka 2.0First glance at Akka 2.0
First glance at Akka 2.0
 
Extending ansible
Extending ansibleExtending ansible
Extending ansible
 
Akka in Practice: Designing Actor-based Applications
Akka in Practice: Designing Actor-based ApplicationsAkka in Practice: Designing Actor-based Applications
Akka in Practice: Designing Actor-based Applications
 
Go database/sql
Go database/sqlGo database/sql
Go database/sql
 
ChefConf 2014 - AWS OpsWorks Under The Hood
ChefConf 2014 - AWS OpsWorks Under The HoodChefConf 2014 - AWS OpsWorks Under The Hood
ChefConf 2014 - AWS OpsWorks Under The Hood
 
Real-time search in Drupal. Meet Elasticsearch
Real-time search in Drupal. Meet ElasticsearchReal-time search in Drupal. Meet Elasticsearch
Real-time search in Drupal. Meet Elasticsearch
 
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
 
Terraform day02
Terraform day02Terraform day02
Terraform day02
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous ArchitecturesUnderstanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
 
Scala.js for large and complex frontend apps
Scala.js for large and complex frontend appsScala.js for large and complex frontend apps
Scala.js for large and complex frontend apps
 
Load test REST APIs using gatling
Load test REST APIs using gatlingLoad test REST APIs using gatling
Load test REST APIs using gatling
 
Building an aws sdk for Perl - Granada Perl Workshop 2014
Building an aws sdk for Perl - Granada Perl Workshop 2014Building an aws sdk for Perl - Granada Perl Workshop 2014
Building an aws sdk for Perl - Granada Perl Workshop 2014
 
20150627 bigdatala
20150627 bigdatala20150627 bigdatala
20150627 bigdatala
 

Similar to Testing in Scala by Adform research

ScalaCheck
ScalaCheckScalaCheck
ScalaCheck
BeScala
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
Luka Zakrajšek
 

Similar to Testing in Scala by Adform research (20)

The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
ScalaCheck
ScalaCheckScalaCheck
ScalaCheck
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinay
 
Building XWiki
Building XWikiBuilding XWiki
Building XWiki
 
How Scala promotes TDD
How Scala promotes TDDHow Scala promotes TDD
How Scala promotes TDD
 
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
 
Scala in the Wild
Scala in the WildScala in the Wild
Scala in the Wild
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Distributed Model Validation with Epsilon
Distributed Model Validation with EpsilonDistributed Model Validation with Epsilon
Distributed Model Validation with Epsilon
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Tdd
TddTdd
Tdd
 
pull requests I sent to scala/scala (ny-scala 2019)
pull requests I sent to scala/scala (ny-scala 2019)pull requests I sent to scala/scala (ny-scala 2019)
pull requests I sent to scala/scala (ny-scala 2019)
 
Scala Frustrations
Scala FrustrationsScala Frustrations
Scala Frustrations
 
Mastering PowerShell Testing with Pester
Mastering PowerShell Testing with PesterMastering PowerShell Testing with Pester
Mastering PowerShell Testing with Pester
 
Gradle
GradleGradle
Gradle
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
 

More from Vasil Remeniuk

Spark Intro by Adform Research
Spark Intro by Adform ResearchSpark Intro by Adform Research
Spark Intro by Adform Research
Vasil Remeniuk
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius Valatka
Vasil Remeniuk
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
Vasil Remeniuk
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex Gryzlov
Vasil Remeniuk
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex Gryzlov
Vasil Remeniuk
 
Spark by Adform Research, Paulius
Spark by Adform Research, PauliusSpark by Adform Research, Paulius
Spark by Adform Research, Paulius
Vasil Remeniuk
 
Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)
Vasil Remeniuk
 
SBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaSBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius Valatka
Vasil Remeniuk
 

More from Vasil Remeniuk (20)

Product Minsk - РТБ и Программатик
Product Minsk - РТБ и ПрограмматикProduct Minsk - РТБ и Программатик
Product Minsk - РТБ и Программатик
 
Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14
 
Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14
 
Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3
 
Spark Intro by Adform Research
Spark Intro by Adform ResearchSpark Intro by Adform Research
Spark Intro by Adform Research
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius Valatka
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex Gryzlov
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex Gryzlov
 
Spark by Adform Research, Paulius
Spark by Adform Research, PauliusSpark by Adform Research, Paulius
Spark by Adform Research, Paulius
 
Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)
 
SBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaSBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius Valatka
 
Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2
 
Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform Research
 
Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1
 
Cassandra + Spark + Elk
Cassandra + Spark + ElkCassandra + Spark + Elk
Cassandra + Spark + Elk
 
Опыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событияхОпыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событиях
 
ETL со Spark
ETL со SparkETL со Spark
ETL со Spark
 
Funtional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWTFuntional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWT
 
Vaadin+Scala
Vaadin+ScalaVaadin+Scala
Vaadin+Scala
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformLess Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

Testing in Scala by Adform research

  • 2. Concepts: Types of Tests Technology Business GlobalLocal Unit Integration Functional Acceptance
  • 3. Unit Tests • Check very specific functionality of your code • Assumes everything else works (mocking) • Test one specific/technical thing • e.g. test your Hadoop job locally, given money in DKK, currency conversion to EUR is called once
  • 4. Integration Tests • Check that all components work together • Includes real components, databases, files, etc. • Test the connectivity of components • e.g. run a job on a development Hadoop cluster, given sample data expected output is written
  • 5. Functional Tests • Test your product against the functionality you developed • Use real components, real data • E.g. run job on a live cluster, given a days worth of data the output is correct (as expected according to specification)
  • 6. Acceptance Tests • Final tests performed by your client before “accepting the product” • Real components, real data, output is correct, performance is acceptable, client is happy
  • 7. Concepts: Testing Styles • TDD: Test Driven Development • BDD: Behavior Driven Development
  • 8. Test Driven Development • Write an interface (trait) for the behavior • Write an empty implementation • Write your unit tests • Make the code compile and tests fail • Correct the implementation • Make the tests pass !
  • 9. Behavior Driven Development • Same idea, just write more functional tests (define behavior)
  • 10. Testing in Scala • For every class in src/main/scala write a test class in src/test/scala • Test classes ~ Test suites • Methods ~ Tests • Run the suit and see the output
  • 11. Testing Libraries/Frameworks • Java: JUnit, TestNG (can be used with scala) • Scala: ScalaTest, Specs2 • Mocking: ScalaMock, EasyMock, JMock, Mockito • Property Testing: ScalaCheck • UI Testing: Selenium
  • 12. • Very similar to Specs2, maybe more flexible, mainly choice of taste • Integrates with sbt, IntelliJ • Integrates with Mockito, ScalaCheck libraryDependencies += "org.scalatest" %% "scalatest" % "2.2.1" % "test"
  • 13. Using ScalaTest import org.scalatest.FunSuite class SetSuite extends FunSuite { test("An empty Set should have size 0") { assert(Set.empty.size == 0) } test("Invoking head on an empty Set should produce NoSuchElementException") { intercept[NoSuchElementException] { Set.empty.head } } }
  • 14.
  • 15.
  • 16.
  • 17. Style Traits • ScalaTest allows you to mix in a testing style you like: • FunSuite • FlatSpec • FunSpec • WordSpec • PropSpec • etc. • http://www.scalatest.org/user_guide/selecting_a_style
  • 22. Testing Styles • ScalaTest recommends having an abstract class with the specs and other traits you like package com.mycompany.myproject import org.scalatest._ abstract class UnitSpec extends FlatSpec with Matchers with OptionValues with Inside with Inspectors package com.mycompany.myproject import org.scalatest._ class MySpec extends UnitSpec { // Your tests here }
  • 23. Fixtures • Your tests may need some setting up and tearing down • ScalaTest has many ways of doing this • http://www.scalatest.org/user_guide/sharing_fixtures
  • 24.
  • 25. Matchers • ScalaTest has lots of syntactic sugar to express your desires result should equal (3) result should have size 10 string should fullyMatch regex """(-)?(d+)(.d*)?""" result1 should not be an [Orangutan] sevenDotOh should equal (6.9 +- 0.2) "howdy" should contain oneOf ('a', 'b', 'c', 'd') (Array("Doe", "Ray", "Me") should contain oneOf ("X", "RAY", "BEAM")) (after being lowerCased) List(0, 1, 2, 2, 99, 3, 3, 3, 5) should contain inOrder (1, 2, 3) map should (contain key ("two") and not contain value (7)) This is Scala Code !!
  • 26. Mocking • You should always code against interfaces (traits) • If you do, testing is easier, since you can mock your dependencies! val m = mock[Turtle] m.expects.forward(10.0) twice m1 returns 42 m2 expects ("this", "that") returning "the other"
  • 27. Property Based Testing • New and exciting way of testing your code! • Instead of examples, you specify properties (higher order testing!) • E.g. when you concatenate two lists, new lengths is sum of lengths • ScalaCheck then generates random inputs and runs many tests • This can catch MANY corner cases you never expect!
  • 28. ScalaCheck import org.scalacheck.Gen val propConcatLists = forAll { (l1: List[Int], l2: List[Int]) => l1.size + l2.size == (l1 ::: l2).size } + OK, passed 100 tests. val propSqrt = forAll { (n: Int) => scala.math.sqrt(n*n) == n } ! Falsified after 1 passed tests: > -1
  • 29. ScalaCheck: Generators val genLeaf = value(Leaf) val genNode = for { v <- arbitrary[Int] left <- genTree right <- genTree } yield Node(left, right, v) def genTree: Gen[Tree] = oneOf(genLeaf, genNode) Option[Tree] = Some(Node(Leaf,Node(Node(Node(Node(Node(Node(Leaf,Leaf,- 71),Node(Leaf,Leaf,-49),17),Leaf,-20),Leaf,-7),Node(Node(Leaf,Leaf,26),Leaf,- 3),49),Leaf,84),-29))
  • 31. Scoverage • Produces test coverage reports • Measures how many statements are tested • Only works with Scala 2.11
  • 32.
  • 33. Testing Scalding Jobs HOMEWORK: use ScalaTest instead of Specs2