SlideShare a Scribd company logo
testing spray.io
in 45 minutes
The Plan
● What spray is
● What we are testing
● How
Spray
“an open-source toolkit for building
REST/HTTP-based integration layers on top of
Scala and Akka”
Spray
“an open-source toolkit for building
REST/HTTP-based integration layers on top of
Scala and Akka”
Library to wrap services with REST API
REST API
● request routing
● (un)marshalling to / from domain objects
● authentication / authorization
● encoding / decoding (compression)
● serving static content
● caching
REST API
● request routing - headers, params and paths
● (un)marshalling to / from domain objects - req/resp entity
● authentication / authorization - directives
● encoding / decoding (compression) - Gzip, Deflate
● serving static content - the same way as request routing
● caching - some of
Example
libraryDependencies ++= {
val akkaV = "2.3.7"
val sprayV = "1.3.2"
Seq(
"com.typesafe.akka" %% "akka-actor" % akkaV,
"io.spray" %% "spray-can" % sprayV,
"io.spray" %% "spray-routing" % sprayV,
"io.spray" %% "spray-testkit" % sprayV % "test",
"org.scalatest" %% "scalatest" % "2.2.4" % "test")
}
Example
import scala.concurrent.duration._
import akka.actor.{Props, ActorSystem}
import akka.io.IO
import akka.pattern.ask
import akka.util.Timeout
import spray.can.Http
object App extends scala.App {
implicit val system = ActorSystem("system")
val service = system.actorOf( Props(new RestService), "rest")
implicit val timeout = Timeout(5.seconds)
IO(Http) ? Http.Bind(service, interface = "localhost", port = 8080)
}
Example - not testable
import spray.routing.HttpServiceActor
class RestService extends HttpServiceActor {
def receive = runRoute(route)
def route =
get {
complete( "ok")
}
}
Example - extract trait
import spray.routing.HttpService
trait SimpleService extends HttpService {
def simpleRoute =
get {
complete( "ok")
}
}
Example - replace route
class RestService extends HttpServiceActor
with SimpleService {
def receive = runRoute(route)
def route =
simpleRoute
}
Example - test
import org.scalatest. {Matchers, FlatSpec}
import spray.testkit.ScalatestRouteTest
class SimpleServiceSpec extends FlatSpec with Matchers
with ScalatestRouteTest
with SimpleService {
def actorRefFactory = system // boilerplate
"A SimpleService" should "return 'ok' for GET request on /" in {
Get("/") ~> simpleRoute ~> check {
responseAs[ String] should be ("ok")
}
}
}
Test API
status.intValue
headers
responseAs[T] // (un)marshalling - String for free
rejections // little tricky when want to test deeper
Get("/users?format=pretty" )
Post("/user", """{"name": "pawel"}""" )
Put("/user/1", """{"name": "kopiczko"}""" )
Delete("/user/1")
Get("/mail/all") ~> Authorization(BasicHttpCredentials ("pawel", ""))
Test Rejection
def deleteRoute =
delete {
path("user" / IntNumber) { id =>
userService.delete(id)
complete( "Deleted user with id " + id)
}
}
Get("/user/1") ~> deleteRoute ~> check {
rejection should be ( MethodRejection (HttpMethods.DELETE))
}
OK, but...
Test Rejection
Get("/user/1") ~> deleteRoute ~> check {
status.intValue should be ( 405)
}
[info] - should not allow GET request on /user *** FAILED ***
[info] Request was rejected with List(MethodRejection(DELETE))
Test Rejection
Get("/user/1") ~> {
handleRejections( RejectionHandler .Default) {
deleteRoute
}
} ~> check {
status.intValue should be ( 405)
}
OK
Dependency Injection
Route is a method - pass arguments
def userRoute(service: UserService) =
get("user" / IntNumber) { id =>
complete {
userService.get(id)
}
}
Get("/user/1") ~> userRoute(userServiceMock) ~> check
Dependency Injection
● Test the REST layer responsibility
● Do NOT test underlying services
● There is another place for that
http://www.slideshare.net/kopiczko/scala45-spray-test-45539693
http://goo.gl/YuL3On

More Related Content

What's hot

Hackathon presentation
Hackathon presentationHackathon presentation
Hackathon presentation
Dev Patel
 
Appengine Java Night #2 Lt
Appengine Java Night #2 LtAppengine Java Night #2 Lt
Appengine Java Night #2 Lt
Shinichi Ogawa
 

What's hot (20)

Consul presentation
Consul presentationConsul presentation
Consul presentation
 
Airflow and supervisor
Airflow and supervisorAirflow and supervisor
Airflow and supervisor
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's Finagle
 
Readme
ReadmeReadme
Readme
 
Hackathon presentation
Hackathon presentationHackathon presentation
Hackathon presentation
 
Reactive streams processing using Akka Streams
Reactive streams processing using Akka StreamsReactive streams processing using Akka Streams
Reactive streams processing using Akka Streams
 
Retrofit
RetrofitRetrofit
Retrofit
 
Prometheus meets Consul -- Consul Casual Talks
Prometheus meets Consul -- Consul Casual TalksPrometheus meets Consul -- Consul Casual Talks
Prometheus meets Consul -- Consul Casual Talks
 
Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams
 
Distributed Eventing in OSGi
Distributed Eventing in OSGiDistributed Eventing in OSGi
Distributed Eventing in OSGi
 
Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018
Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018
Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018
 
Appengine Java Night #2 Lt
Appengine Java Night #2 LtAppengine Java Night #2 Lt
Appengine Java Night #2 Lt
 
Parse Server Open Source
Parse Server Open SourceParse Server Open Source
Parse Server Open Source
 
From Zero to Stream Processing
From Zero to Stream ProcessingFrom Zero to Stream Processing
From Zero to Stream Processing
 
Integration testing for salt states using aws ec2 container service
Integration testing for salt states using aws ec2 container serviceIntegration testing for salt states using aws ec2 container service
Integration testing for salt states using aws ec2 container service
 
Retrofit
RetrofitRetrofit
Retrofit
 
OASGraph LoopBack 4 Integration
OASGraph LoopBack 4 IntegrationOASGraph LoopBack 4 Integration
OASGraph LoopBack 4 Integration
 
Intelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStackIntelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStack
 
Next generation actors with Akka
Next generation actors with AkkaNext generation actors with Akka
Next generation actors with Akka
 
Retrofit library for android
Retrofit library for androidRetrofit library for android
Retrofit library for android
 

Viewers also liked

Tema1. Introduccion molinux
Tema1. Introduccion molinuxTema1. Introduccion molinux
Tema1. Introduccion molinux
jpalencia
 
KW Outfront Magazine Online Edition Sept/Oct 2010
KW Outfront Magazine Online Edition Sept/Oct 2010KW Outfront Magazine Online Edition Sept/Oct 2010
KW Outfront Magazine Online Edition Sept/Oct 2010
Keller Williams Careers
 
Girsberger Benelux - Office collection
Girsberger Benelux - Office collectionGirsberger Benelux - Office collection
Girsberger Benelux - Office collection
Architectura
 
COMO PUBLICAR ARCHIVOS EN EL BLOG
COMO PUBLICAR ARCHIVOS EN EL BLOG COMO PUBLICAR ARCHIVOS EN EL BLOG
COMO PUBLICAR ARCHIVOS EN EL BLOG
TJVN2
 
Taskhero deck 10.15.12
Taskhero deck 10.15.12Taskhero deck 10.15.12
Taskhero deck 10.15.12
taskhero
 
Programa #llopasfera14
Programa #llopasfera14Programa #llopasfera14
Programa #llopasfera14
Llopa Sfera
 
06 10-14 - acta pleno nº 16
06 10-14 - acta pleno nº 1606 10-14 - acta pleno nº 16
06 10-14 - acta pleno nº 16
UPyDNovelda
 

Viewers also liked (20)

Water repellency & waterproof & repellency test method
Water repellency & waterproof & repellency test methodWater repellency & waterproof & repellency test method
Water repellency & waterproof & repellency test method
 
Water repellency of fabrics
Water repellency of fabricsWater repellency of fabrics
Water repellency of fabrics
 
Fabric tensile strength test
Fabric tensile strength testFabric tensile strength test
Fabric tensile strength test
 
Dunya Paralari Gezgin
Dunya Paralari GezginDunya Paralari Gezgin
Dunya Paralari Gezgin
 
Consejotecnicoescolarfaseintensiva20152016(2)
Consejotecnicoescolarfaseintensiva20152016(2)Consejotecnicoescolarfaseintensiva20152016(2)
Consejotecnicoescolarfaseintensiva20152016(2)
 
Tema1. Introduccion molinux
Tema1. Introduccion molinuxTema1. Introduccion molinux
Tema1. Introduccion molinux
 
KW Outfront Magazine Online Edition Sept/Oct 2010
KW Outfront Magazine Online Edition Sept/Oct 2010KW Outfront Magazine Online Edition Sept/Oct 2010
KW Outfront Magazine Online Edition Sept/Oct 2010
 
Girsberger Benelux - Office collection
Girsberger Benelux - Office collectionGirsberger Benelux - Office collection
Girsberger Benelux - Office collection
 
CES 2015 - Journée 1 vue par EMOTIC
CES 2015 - Journée 1 vue par EMOTICCES 2015 - Journée 1 vue par EMOTIC
CES 2015 - Journée 1 vue par EMOTIC
 
AguayoAbogados
AguayoAbogadosAguayoAbogados
AguayoAbogados
 
COMO PUBLICAR ARCHIVOS EN EL BLOG
COMO PUBLICAR ARCHIVOS EN EL BLOG COMO PUBLICAR ARCHIVOS EN EL BLOG
COMO PUBLICAR ARCHIVOS EN EL BLOG
 
U4 jou231 mobile_message
U4 jou231 mobile_messageU4 jou231 mobile_message
U4 jou231 mobile_message
 
Dragonslayer weekly update 17 aug 12
Dragonslayer weekly update 17 aug 12 Dragonslayer weekly update 17 aug 12
Dragonslayer weekly update 17 aug 12
 
Taskhero deck 10.15.12
Taskhero deck 10.15.12Taskhero deck 10.15.12
Taskhero deck 10.15.12
 
Programa #llopasfera14
Programa #llopasfera14Programa #llopasfera14
Programa #llopasfera14
 
BB Family FB Group _ Jul -15-2010
BB Family FB Group _ Jul -15-2010BB Family FB Group _ Jul -15-2010
BB Family FB Group _ Jul -15-2010
 
Angola cessaf final_2-3-2013
Angola cessaf final_2-3-2013Angola cessaf final_2-3-2013
Angola cessaf final_2-3-2013
 
Q7 es - Iniciativas locales de impulso a la innovación empresarial (ES)
Q7 es - Iniciativas locales de impulso a la innovación empresarial (ES)Q7 es - Iniciativas locales de impulso a la innovación empresarial (ES)
Q7 es - Iniciativas locales de impulso a la innovación empresarial (ES)
 
06 10-14 - acta pleno nº 16
06 10-14 - acta pleno nº 1606 10-14 - acta pleno nº 16
06 10-14 - acta pleno nº 16
 
Bomba Dosadora Mroy
Bomba Dosadora MroyBomba Dosadora Mroy
Bomba Dosadora Mroy
 

Similar to Scala45 spray test

Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
b_kathir
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin
 
Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]
Karel Minarik
 
Nexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and SprayNexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and Spray
Matthew Farwell
 

Similar to Scala45 spray test (20)

Building scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTPBuilding scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTP
 
JAX-RS.next
JAX-RS.nextJAX-RS.next
JAX-RS.next
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
 
scalaphx-akka-http
scalaphx-akka-httpscalaphx-akka-http
scalaphx-akka-http
 
Federico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesFederico Feroldi - Scala microservices
Federico Feroldi - Scala microservices
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
StackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStackStackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStack
 
Spray human talks
Spray human talksSpray human talks
Spray human talks
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rs
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
Rack
RackRack
Rack
 
Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅
 
Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]
 
Nexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and SprayNexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and Spray
 
Resthub lyonjug
Resthub lyonjugResthub lyonjug
Resthub lyonjug
 
Rack
RackRack
Rack
 
GraphQL API in Clojure
GraphQL API in ClojureGraphQL API in Clojure
GraphQL API in Clojure
 

Recently uploaded

AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
Alluxio, Inc.
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 

Recently uploaded (20)

Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 

Scala45 spray test

  • 2. The Plan ● What spray is ● What we are testing ● How
  • 3. Spray “an open-source toolkit for building REST/HTTP-based integration layers on top of Scala and Akka”
  • 4. Spray “an open-source toolkit for building REST/HTTP-based integration layers on top of Scala and Akka” Library to wrap services with REST API
  • 5. REST API ● request routing ● (un)marshalling to / from domain objects ● authentication / authorization ● encoding / decoding (compression) ● serving static content ● caching
  • 6. REST API ● request routing - headers, params and paths ● (un)marshalling to / from domain objects - req/resp entity ● authentication / authorization - directives ● encoding / decoding (compression) - Gzip, Deflate ● serving static content - the same way as request routing ● caching - some of
  • 7. Example libraryDependencies ++= { val akkaV = "2.3.7" val sprayV = "1.3.2" Seq( "com.typesafe.akka" %% "akka-actor" % akkaV, "io.spray" %% "spray-can" % sprayV, "io.spray" %% "spray-routing" % sprayV, "io.spray" %% "spray-testkit" % sprayV % "test", "org.scalatest" %% "scalatest" % "2.2.4" % "test") }
  • 8. Example import scala.concurrent.duration._ import akka.actor.{Props, ActorSystem} import akka.io.IO import akka.pattern.ask import akka.util.Timeout import spray.can.Http object App extends scala.App { implicit val system = ActorSystem("system") val service = system.actorOf( Props(new RestService), "rest") implicit val timeout = Timeout(5.seconds) IO(Http) ? Http.Bind(service, interface = "localhost", port = 8080) }
  • 9. Example - not testable import spray.routing.HttpServiceActor class RestService extends HttpServiceActor { def receive = runRoute(route) def route = get { complete( "ok") } }
  • 10. Example - extract trait import spray.routing.HttpService trait SimpleService extends HttpService { def simpleRoute = get { complete( "ok") } }
  • 11. Example - replace route class RestService extends HttpServiceActor with SimpleService { def receive = runRoute(route) def route = simpleRoute }
  • 12. Example - test import org.scalatest. {Matchers, FlatSpec} import spray.testkit.ScalatestRouteTest class SimpleServiceSpec extends FlatSpec with Matchers with ScalatestRouteTest with SimpleService { def actorRefFactory = system // boilerplate "A SimpleService" should "return 'ok' for GET request on /" in { Get("/") ~> simpleRoute ~> check { responseAs[ String] should be ("ok") } } }
  • 13. Test API status.intValue headers responseAs[T] // (un)marshalling - String for free rejections // little tricky when want to test deeper Get("/users?format=pretty" ) Post("/user", """{"name": "pawel"}""" ) Put("/user/1", """{"name": "kopiczko"}""" ) Delete("/user/1") Get("/mail/all") ~> Authorization(BasicHttpCredentials ("pawel", ""))
  • 14. Test Rejection def deleteRoute = delete { path("user" / IntNumber) { id => userService.delete(id) complete( "Deleted user with id " + id) } } Get("/user/1") ~> deleteRoute ~> check { rejection should be ( MethodRejection (HttpMethods.DELETE)) } OK, but...
  • 15. Test Rejection Get("/user/1") ~> deleteRoute ~> check { status.intValue should be ( 405) } [info] - should not allow GET request on /user *** FAILED *** [info] Request was rejected with List(MethodRejection(DELETE))
  • 16. Test Rejection Get("/user/1") ~> { handleRejections( RejectionHandler .Default) { deleteRoute } } ~> check { status.intValue should be ( 405) } OK
  • 17. Dependency Injection Route is a method - pass arguments def userRoute(service: UserService) = get("user" / IntNumber) { id => complete { userService.get(id) } } Get("/user/1") ~> userRoute(userServiceMock) ~> check
  • 18. Dependency Injection ● Test the REST layer responsibility ● Do NOT test underlying services ● There is another place for that