SlideShare uma empresa Scribd logo
1 de 47
Baixar para ler offline
Workshop
SPOCK: Testing (in the) Enterprise!
Fernando Redondo
@pronoide_fer
Roadmap
Whoami
• Pronoide’s owner and manager
• Currently working for Hybris (SAP) as technical
trainer
• Java & Friends trainer for last ten years
• Doing things with Java from 1999 on
• Computer Engineer
• Happily married and proud father of two children
• Not that Trekky yet (Sure!)
Brief introduction
• Groovy based testing and
specification framework
• Can test anything that runs
inside the JVM (even Java code)
• Beautiful and highly expressive specification language
• Compatible with most IDEs, build tools, and continuous
integration servers (JUnit runner)
Terminology and definitions
• Spock lets you write specifications that
describe expected features (properties,
aspects) exhibited by a system of interest.
• The system of interest could be anything between a single class
and a whole application, and is also called system under
specification (SUS).
• The description of a feature starts from a specific snapshot of the
SUS and its collaborators; this snapshot is called the feature’s
fixture.
Brief introduction
How do I start with Maven?
-
How do I start with Gradle?
Hands on!
Before start, you have to…
1. Start Groovy/Grails Tool Suite 3.6 (GGTS) and create a workspace (remember to
run it with a JDK and install the gradle extension for eclipse). Groovy 2.4 compiler
as well. Or just use gradle and a test editor.
1. Download http://pronoide.com/downloads/spock-workshop-2015.zip
and unzip it into workspace folder.
2. Hold on! Please wait me right here…
Stage I: Import the workshop project
i. Import gradle Project (enterprise.mission)
Specifications
Test classes are known as Specifications
• All specifications (Specs) must extend
from spock.lang.Specification
• Each specification must have at least ONE test method,
all of these are called feature methods
• The most simple assert within a feature method is
the expect block, all its sentences must be evaluated to
true so that the feature will be OK
A very simple specification
Specifications
Stage II: Creating Specs
Complete the following specification and acomplish the challenges
(org.startrek.challenges.n01.RacesSpec)
Did you get it right? (org.startrek.solutions.n01.RacesSpec)
Stage II: Creating Specs
Stage II: Creating Specs
• Run the spec class as JUnit test
• Or execute the test gradle task (gradle quick task launcher)
Specfication methods
Within any specification we can found:
• Feature methods (or test methods) with
diferent blocks of code for stating the
scenario under spec
• Fixture methods that will be called automatically before
or after any single feature methods or before and after
the specification:
o setup, cleanup, setupSpec and cleanupSpeck
• Helper methods that can be called at any time from
other methods and can be convenient for code clarity
and code reuse
Stage III: Inside the Specs
Complete the following specification and acomplish the challenge
(org.startrek.challenges.n02.VoyageSpec)
Stage III: Inside the Specs
This is not rocket science (org.startrek.solutions.n02.VoyageSpec)
Feature method blocks
Inside any feature method we can come
across different kinds of phases or blocks:
• setup and/or cleanup, at most once per spec,
to inicialise and dispose stuff for that particular feature
(don’t mix up with fixtures). The setup block can be
omitted or aliased with given for readability purpouses.
We can create kind of different given sections with and
• An expect block may only contain conditions and
variable definitions. It is useful in situations where it is
more natural to describe stimulus and expected
response in a single expression
Stage IV: Inside the feature
Complete the following feature methods and probe your courage
(org.startrek.challenges.n03.SpaceshipSpec)
Easy peasy!! (org.startrek.solutions.n03.SpaceshipSpec)
Stage IV: Inside the feature
Feature method blocks
These are the kinds of blocks within a
feature method (continuation):
• when and then blocks always occur
together. They describe a stimulus and the expected
response
– when blocks can contain arbitrary code
– then blocks are restricted to conditions, exception conditions,
interactions, and variable definitions (which means more
options available than for expect blocks)
– There can be multiples pair ocurrencies when/then within a
feature
Stage IV: Inside the feature
Fill in the next feature method if you dare!
(org.startrek.challenges.n03.StarfleetSpec)
It was piece of cake!! (org.startrek.solutions.n03.SpaceshipSpec)
Stage IV: Inside the feature
Feature method blocks
These are the kinds of blocks (cont.):
• A where block always comes last in a feature method, and cannot be
repeated. It is used to write data-driven feature
methods. As a matter of convenience it can be written in two
different ways:
– A row per variable with the << symbol
– A column per variable with the | symbol
• A data-drive feature method can also be annotated with @unroll
– the method will be invoked multiple times with the provider data variables
– these can be used in the method description with placeholders (#)
– For each iteration the placeholders are replaced with correct values
Stage IV: Inside the feature
Things get tougher! (org.startrek.challenges.n03.WeaponsDamageSpec)
As easy as pie!! (org.startrek.solutions.n03.WeaponsDamageSpec)
Stage IV: Inside the feature
Testing exceptions
In order to deal with specification that
throw or not exceptions, Spock provides
the following exception conditions
• thrown(ExceptionClass) and notThrow(ExceptionClass)
• It’s also possible to get the exception instance, to access
its attributes:
def ex=thrown()
Or
ExceptionClass ex=thrown()
Stage V: Exception Conditions
Complete these features (org.startrek.challenges.n04.DestructionSpec)
Keep it up! (org.startrek.solutions.n04.DestructionSpec)
Stage IV: Inside the feature
Interaction-based testing is a design and
testing technique that focusing more on the
behavior of objects rather than their state, it
explores how the object(s) under spec interact, by way of
method calls, with their collaborators
• We need to mock the collaborator implementations via
def colaborator=Mock(Class) Or Class colaborator=Mock()
• Mocks are usually created using Dynamic Proxies or CGLib
• We can track interactions with collaborators within then block:
when:
spock.teletransport()
then:
1 * transporter.use()
Interactions
Stage VI: Interactions
Write down this feature method
(org.startrek.challenges.n05.ShipManagementSpec)
Clue: https://code.google.com/p/spock/wiki/Interactions#Cardinalities
It’s not that complicated, is it?
(org.startrek.solutions.n05. ShipManagementSpec)
Stage VI: Interactions
Useful stuff
In our daily life with Spock, we´ll make use of:
• Share objects among feature via @Shared class
attributes, other way they won’t share them
• There are two kinds of conditions to validate a feature: Implicit and
Explicit. Implicit conditions appear within expect and then blocks. To
use conditions in other places, you can use assert keyword
• Sometimes feature methods are large or contain duplicated code. It
can make sense to introduce helper methods
• Specifications as Documentation, Spock provides a way to attach
textual descriptions to blocks
When: “everything start”
• You can leverage the use of Hamcrest matchers (assertThat is
aliased just as that or expect)
Stage VI: Other mechanisms
In the following spec identify with a comment which mechanisms
are used (org.startrek.challenges.n06.MoviesSpec)
No brainer (org.startrek.solutions.n06. MoviesSpec)
Stage VI: Other mechanisms
Extensions
Spock offers lots of functionality for specs. But, there is
always a time when something else is needed. Spock
provides an interception-based extension mechanism.
Extensions are activated by annotations called directives.
These are some directives:
• @Timeout Sets a timeout for execution of a feature or fixture
• @Ignore Ignores a feature method
• @IgnoreRest Ignores all feature methods not carrying this annotation
• @IgnoreIf To ignore a feature method under certain conditions
• @FailsWith Expects a feature method to complete abruptly
• @Requires To execute a feature method under certain conditions
• @Stepwise executes features in the order that they are declared
• @Title and @Narrative To attach a natural-language name to a spec
• @Issue indicates that a feature/spec relates to one/more issues in an external tracking
system
• @Subject To indicate one or more subjects of a spec
• Many more! and you can also create your own ones…
Extensions
The Spock Spring extension allows Spock to integrate
with Spring's TestContext framework
• the extension uses Spring API
• change add dependencies to our build.gradle:
spock-spring, spring-context and spring-test
Stage VI: Extensions
Let’s leave that for another time… ;)
Extra ball: Geb!
Geb is a framework for automatization of functional
web testing. It is based on the following technologies:
• Groovy Language (and it’s incredible with Spock)
• Selenium WebDriver
• JQuery CSS Content Selector
• Page Object Model
To leveage it, we have to
• change add dependencies to our build.gradle:
testCompile 'org.gebish:geb-spock:0.10.0'
testCompile "org.seleniumhq.selenium:selenium-chrome-driver:2.43.1”
• Download and configure our driver (automated browser) in
src/test/resources/GebConfig.groovy
Create a simple driver configuration & download the driver
(src/test/resources/GebConfig.groovy)
Extra ball: Geb!
Let’s perform a search for apock in memory-alpha.org
(org.startrek.challenges.n07.WebNavigationSpec.groovy)
Extra ball: Geb!
That was great! But, Can YOU do it in a better way?
Extra ball: Geb!
Let’s keep it simple an reusable! Functional Spec.
(org.startrek.solutions.n07.WebNavigationSpec2.groovy)
Extra ball: Geb!
Let’s keep it simple an reusable! Reusable Page Model.
(org.startrek.solutions.n07. MemoryAlphaPage.groovy and
org.startrek.solutions.n07. MemoryAlphaResultsPage.groovy )
Extra ball: Geb!
And that’s it. Thanks!
fredondo@pronoide.com
@pronoide_fer

Mais conteúdo relacionado

Mais procurados

[OWASP Poland Day] A study of Electron security
[OWASP Poland Day] A study of Electron security[OWASP Poland Day] A study of Electron security
[OWASP Poland Day] A study of Electron securityOWASP
 
Defending against Java Deserialization Vulnerabilities
 Defending against Java Deserialization Vulnerabilities Defending against Java Deserialization Vulnerabilities
Defending against Java Deserialization VulnerabilitiesLuca Carettoni
 
Stranger Danger: Securing Third Party Components (Tech2020)
Stranger Danger: Securing Third Party Components (Tech2020)Stranger Danger: Securing Third Party Components (Tech2020)
Stranger Danger: Securing Third Party Components (Tech2020)Guy Podjarny
 
DevSecCon Tel Aviv 2018 - End2End containers SSDLC by Vitaly Davidoff
DevSecCon Tel Aviv 2018 - End2End containers SSDLC by Vitaly DavidoffDevSecCon Tel Aviv 2018 - End2End containers SSDLC by Vitaly Davidoff
DevSecCon Tel Aviv 2018 - End2End containers SSDLC by Vitaly DavidoffDevSecCon
 
SyScan 2016 - Remote code execution via Java native deserialization
SyScan 2016 - Remote code execution via Java native deserializationSyScan 2016 - Remote code execution via Java native deserialization
SyScan 2016 - Remote code execution via Java native deserializationDavid Jorm
 
The old is new, again. CVE-2011-2461 is back!
The old is new, again. CVE-2011-2461 is back!The old is new, again. CVE-2011-2461 is back!
The old is new, again. CVE-2011-2461 is back!Luca Carettoni
 
An Abusive Relationship with AngularJS by Mario Heiderich - CODE BLUE 2015
An Abusive Relationship with AngularJS by Mario Heiderich - CODE BLUE 2015An Abusive Relationship with AngularJS by Mario Heiderich - CODE BLUE 2015
An Abusive Relationship with AngularJS by Mario Heiderich - CODE BLUE 2015CODE BLUE
 
Automating Security Testing with the OWTF
Automating Security Testing with the OWTFAutomating Security Testing with the OWTF
Automating Security Testing with the OWTFJerod Brennen
 
[OWASP Poland Day] Security knowledge framework
[OWASP Poland Day] Security knowledge framework[OWASP Poland Day] Security knowledge framework
[OWASP Poland Day] Security knowledge frameworkOWASP
 
[OWASP Poland Day] Saving private token
[OWASP Poland Day] Saving private token[OWASP Poland Day] Saving private token
[OWASP Poland Day] Saving private tokenOWASP
 
Abusing Java Remote Interfaces
Abusing Java Remote InterfacesAbusing Java Remote Interfaces
Abusing Java Remote Interfacesjuanvazquezslides
 
[Wroclaw #5] OWASP Projects: beyond Top 10
[Wroclaw #5] OWASP Projects: beyond Top 10[Wroclaw #5] OWASP Projects: beyond Top 10
[Wroclaw #5] OWASP Projects: beyond Top 10OWASP
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Christian Schneider
 
Java Exploit Analysis .
Java Exploit Analysis .Java Exploit Analysis .
Java Exploit Analysis .Rahul Sasi
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaCODE WHITE GmbH
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)CODE WHITE GmbH
 
SecDevOps - The Operationalisation of Security
SecDevOps -  The Operationalisation of SecuritySecDevOps -  The Operationalisation of Security
SecDevOps - The Operationalisation of SecurityDinis Cruz
 
[Wroclaw #2] Web Application Security Headers
[Wroclaw #2] Web Application Security Headers[Wroclaw #2] Web Application Security Headers
[Wroclaw #2] Web Application Security HeadersOWASP
 
How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)Dave Haeffner
 
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...Christian Schneider
 

Mais procurados (20)

[OWASP Poland Day] A study of Electron security
[OWASP Poland Day] A study of Electron security[OWASP Poland Day] A study of Electron security
[OWASP Poland Day] A study of Electron security
 
Defending against Java Deserialization Vulnerabilities
 Defending against Java Deserialization Vulnerabilities Defending against Java Deserialization Vulnerabilities
Defending against Java Deserialization Vulnerabilities
 
Stranger Danger: Securing Third Party Components (Tech2020)
Stranger Danger: Securing Third Party Components (Tech2020)Stranger Danger: Securing Third Party Components (Tech2020)
Stranger Danger: Securing Third Party Components (Tech2020)
 
DevSecCon Tel Aviv 2018 - End2End containers SSDLC by Vitaly Davidoff
DevSecCon Tel Aviv 2018 - End2End containers SSDLC by Vitaly DavidoffDevSecCon Tel Aviv 2018 - End2End containers SSDLC by Vitaly Davidoff
DevSecCon Tel Aviv 2018 - End2End containers SSDLC by Vitaly Davidoff
 
SyScan 2016 - Remote code execution via Java native deserialization
SyScan 2016 - Remote code execution via Java native deserializationSyScan 2016 - Remote code execution via Java native deserialization
SyScan 2016 - Remote code execution via Java native deserialization
 
The old is new, again. CVE-2011-2461 is back!
The old is new, again. CVE-2011-2461 is back!The old is new, again. CVE-2011-2461 is back!
The old is new, again. CVE-2011-2461 is back!
 
An Abusive Relationship with AngularJS by Mario Heiderich - CODE BLUE 2015
An Abusive Relationship with AngularJS by Mario Heiderich - CODE BLUE 2015An Abusive Relationship with AngularJS by Mario Heiderich - CODE BLUE 2015
An Abusive Relationship with AngularJS by Mario Heiderich - CODE BLUE 2015
 
Automating Security Testing with the OWTF
Automating Security Testing with the OWTFAutomating Security Testing with the OWTF
Automating Security Testing with the OWTF
 
[OWASP Poland Day] Security knowledge framework
[OWASP Poland Day] Security knowledge framework[OWASP Poland Day] Security knowledge framework
[OWASP Poland Day] Security knowledge framework
 
[OWASP Poland Day] Saving private token
[OWASP Poland Day] Saving private token[OWASP Poland Day] Saving private token
[OWASP Poland Day] Saving private token
 
Abusing Java Remote Interfaces
Abusing Java Remote InterfacesAbusing Java Remote Interfaces
Abusing Java Remote Interfaces
 
[Wroclaw #5] OWASP Projects: beyond Top 10
[Wroclaw #5] OWASP Projects: beyond Top 10[Wroclaw #5] OWASP Projects: beyond Top 10
[Wroclaw #5] OWASP Projects: beyond Top 10
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
 
Java Exploit Analysis .
Java Exploit Analysis .Java Exploit Analysis .
Java Exploit Analysis .
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in Java
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (DeepSec Edition)
 
SecDevOps - The Operationalisation of Security
SecDevOps -  The Operationalisation of SecuritySecDevOps -  The Operationalisation of Security
SecDevOps - The Operationalisation of Security
 
[Wroclaw #2] Web Application Security Headers
[Wroclaw #2] Web Application Security Headers[Wroclaw #2] Web Application Security Headers
[Wroclaw #2] Web Application Security Headers
 
How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)
 
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
 

Destaque

Seguridad de las aplicaciones web con Spring Security 3.x
Seguridad de las aplicaciones web con Spring Security 3.xSeguridad de las aplicaciones web con Spring Security 3.x
Seguridad de las aplicaciones web con Spring Security 3.xFernando Redondo Ramírez
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With SpockIT Weekend
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and ProsperKen Kousen
 
Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)jaxLondonConference
 

Destaque (6)

Seguridad de las aplicaciones web con Spring Security 3.x
Seguridad de las aplicaciones web con Spring Security 3.xSeguridad de las aplicaciones web con Spring Security 3.x
Seguridad de las aplicaciones web con Spring Security 3.x
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)
 

Semelhante a Codemotion 2015 spock_workshop

Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for seleniumapoorvams
 
How to crack java script certification
How to crack java script certificationHow to crack java script certification
How to crack java script certificationKadharBashaJ
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@Alex Borsuk
 
DevOps - Boldly Go for Distro
DevOps - Boldly Go for DistroDevOps - Boldly Go for Distro
DevOps - Boldly Go for DistroPaul Boos
 
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 AppAll Things Open
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 
Test Driven Development - Workshop
Test Driven Development - WorkshopTest Driven Development - Workshop
Test Driven Development - WorkshopAnjana Somathilake
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with SeleniumDave Haeffner
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonIneke Scheffers
 
Testing - How Vital and How Easy to use
Testing - How Vital and How Easy to useTesting - How Vital and How Easy to use
Testing - How Vital and How Easy to useUma Ghotikar
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfnofakeNews
 
The Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingThe Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingTim Duckett
 

Semelhante a Codemotion 2015 spock_workshop (20)

Spring IO 2015 Spock Workshop
Spring IO 2015 Spock WorkshopSpring IO 2015 Spock Workshop
Spring IO 2015 Spock Workshop
 
Greach 2015 Spock workshop
Greach 2015 Spock workshopGreach 2015 Spock workshop
Greach 2015 Spock workshop
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
Spock pres
Spock presSpock pres
Spock pres
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
How to crack java script certification
How to crack java script certificationHow to crack java script certification
How to crack java script certification
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
DevOps - Boldly Go for Distro
DevOps - Boldly Go for DistroDevOps - Boldly Go for Distro
DevOps - Boldly Go for Distro
 
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
 
Protractor survival guide
Protractor survival guideProtractor survival guide
Protractor survival guide
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Test Driven Development - Workshop
Test Driven Development - WorkshopTest Driven Development - Workshop
Test Driven Development - Workshop
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
 
Eclipse UI automation
Eclipse UI automationEclipse UI automation
Eclipse UI automation
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomon
 
Testing - How Vital and How Easy to use
Testing - How Vital and How Easy to useTesting - How Vital and How Easy to use
Testing - How Vital and How Easy to use
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
 
The Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingThe Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To Testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 

Último

Exploring ChatGPT Prompt Hacks To Maximally Optimise Your Queries
Exploring ChatGPT Prompt Hacks To Maximally Optimise Your QueriesExploring ChatGPT Prompt Hacks To Maximally Optimise Your Queries
Exploring ChatGPT Prompt Hacks To Maximally Optimise Your QueriesSanjay Willie
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Fact vs. Fiction: Autodetecting Hallucinations in LLMs
Fact vs. Fiction: Autodetecting Hallucinations in LLMsFact vs. Fiction: Autodetecting Hallucinations in LLMs
Fact vs. Fiction: Autodetecting Hallucinations in LLMsZilliz
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 

Último (20)

Exploring ChatGPT Prompt Hacks To Maximally Optimise Your Queries
Exploring ChatGPT Prompt Hacks To Maximally Optimise Your QueriesExploring ChatGPT Prompt Hacks To Maximally Optimise Your Queries
Exploring ChatGPT Prompt Hacks To Maximally Optimise Your Queries
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Fact vs. Fiction: Autodetecting Hallucinations in LLMs
Fact vs. Fiction: Autodetecting Hallucinations in LLMsFact vs. Fiction: Autodetecting Hallucinations in LLMs
Fact vs. Fiction: Autodetecting Hallucinations in LLMs
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 

Codemotion 2015 spock_workshop

  • 1. Workshop SPOCK: Testing (in the) Enterprise! Fernando Redondo @pronoide_fer
  • 3. Whoami • Pronoide’s owner and manager • Currently working for Hybris (SAP) as technical trainer • Java & Friends trainer for last ten years • Doing things with Java from 1999 on • Computer Engineer • Happily married and proud father of two children • Not that Trekky yet (Sure!)
  • 4. Brief introduction • Groovy based testing and specification framework • Can test anything that runs inside the JVM (even Java code) • Beautiful and highly expressive specification language • Compatible with most IDEs, build tools, and continuous integration servers (JUnit runner)
  • 5. Terminology and definitions • Spock lets you write specifications that describe expected features (properties, aspects) exhibited by a system of interest. • The system of interest could be anything between a single class and a whole application, and is also called system under specification (SUS). • The description of a feature starts from a specific snapshot of the SUS and its collaborators; this snapshot is called the feature’s fixture. Brief introduction
  • 6. How do I start with Maven? -
  • 7. How do I start with Gradle?
  • 8.
  • 9.
  • 10. Hands on! Before start, you have to… 1. Start Groovy/Grails Tool Suite 3.6 (GGTS) and create a workspace (remember to run it with a JDK and install the gradle extension for eclipse). Groovy 2.4 compiler as well. Or just use gradle and a test editor. 1. Download http://pronoide.com/downloads/spock-workshop-2015.zip and unzip it into workspace folder. 2. Hold on! Please wait me right here…
  • 11. Stage I: Import the workshop project i. Import gradle Project (enterprise.mission)
  • 12. Specifications Test classes are known as Specifications • All specifications (Specs) must extend from spock.lang.Specification • Each specification must have at least ONE test method, all of these are called feature methods • The most simple assert within a feature method is the expect block, all its sentences must be evaluated to true so that the feature will be OK
  • 13. A very simple specification Specifications
  • 14. Stage II: Creating Specs Complete the following specification and acomplish the challenges (org.startrek.challenges.n01.RacesSpec)
  • 15. Did you get it right? (org.startrek.solutions.n01.RacesSpec) Stage II: Creating Specs
  • 16. Stage II: Creating Specs • Run the spec class as JUnit test • Or execute the test gradle task (gradle quick task launcher)
  • 17. Specfication methods Within any specification we can found: • Feature methods (or test methods) with diferent blocks of code for stating the scenario under spec • Fixture methods that will be called automatically before or after any single feature methods or before and after the specification: o setup, cleanup, setupSpec and cleanupSpeck • Helper methods that can be called at any time from other methods and can be convenient for code clarity and code reuse
  • 18. Stage III: Inside the Specs Complete the following specification and acomplish the challenge (org.startrek.challenges.n02.VoyageSpec)
  • 19. Stage III: Inside the Specs This is not rocket science (org.startrek.solutions.n02.VoyageSpec)
  • 20. Feature method blocks Inside any feature method we can come across different kinds of phases or blocks: • setup and/or cleanup, at most once per spec, to inicialise and dispose stuff for that particular feature (don’t mix up with fixtures). The setup block can be omitted or aliased with given for readability purpouses. We can create kind of different given sections with and • An expect block may only contain conditions and variable definitions. It is useful in situations where it is more natural to describe stimulus and expected response in a single expression
  • 21. Stage IV: Inside the feature Complete the following feature methods and probe your courage (org.startrek.challenges.n03.SpaceshipSpec)
  • 23. Feature method blocks These are the kinds of blocks within a feature method (continuation): • when and then blocks always occur together. They describe a stimulus and the expected response – when blocks can contain arbitrary code – then blocks are restricted to conditions, exception conditions, interactions, and variable definitions (which means more options available than for expect blocks) – There can be multiples pair ocurrencies when/then within a feature
  • 24. Stage IV: Inside the feature Fill in the next feature method if you dare! (org.startrek.challenges.n03.StarfleetSpec)
  • 25. It was piece of cake!! (org.startrek.solutions.n03.SpaceshipSpec) Stage IV: Inside the feature
  • 26. Feature method blocks These are the kinds of blocks (cont.): • A where block always comes last in a feature method, and cannot be repeated. It is used to write data-driven feature methods. As a matter of convenience it can be written in two different ways: – A row per variable with the << symbol – A column per variable with the | symbol • A data-drive feature method can also be annotated with @unroll – the method will be invoked multiple times with the provider data variables – these can be used in the method description with placeholders (#) – For each iteration the placeholders are replaced with correct values
  • 27. Stage IV: Inside the feature Things get tougher! (org.startrek.challenges.n03.WeaponsDamageSpec)
  • 28. As easy as pie!! (org.startrek.solutions.n03.WeaponsDamageSpec) Stage IV: Inside the feature
  • 29. Testing exceptions In order to deal with specification that throw or not exceptions, Spock provides the following exception conditions • thrown(ExceptionClass) and notThrow(ExceptionClass) • It’s also possible to get the exception instance, to access its attributes: def ex=thrown() Or ExceptionClass ex=thrown()
  • 30. Stage V: Exception Conditions Complete these features (org.startrek.challenges.n04.DestructionSpec)
  • 31. Keep it up! (org.startrek.solutions.n04.DestructionSpec) Stage IV: Inside the feature
  • 32. Interaction-based testing is a design and testing technique that focusing more on the behavior of objects rather than their state, it explores how the object(s) under spec interact, by way of method calls, with their collaborators • We need to mock the collaborator implementations via def colaborator=Mock(Class) Or Class colaborator=Mock() • Mocks are usually created using Dynamic Proxies or CGLib • We can track interactions with collaborators within then block: when: spock.teletransport() then: 1 * transporter.use() Interactions
  • 33. Stage VI: Interactions Write down this feature method (org.startrek.challenges.n05.ShipManagementSpec) Clue: https://code.google.com/p/spock/wiki/Interactions#Cardinalities
  • 34. It’s not that complicated, is it? (org.startrek.solutions.n05. ShipManagementSpec) Stage VI: Interactions
  • 35. Useful stuff In our daily life with Spock, we´ll make use of: • Share objects among feature via @Shared class attributes, other way they won’t share them • There are two kinds of conditions to validate a feature: Implicit and Explicit. Implicit conditions appear within expect and then blocks. To use conditions in other places, you can use assert keyword • Sometimes feature methods are large or contain duplicated code. It can make sense to introduce helper methods • Specifications as Documentation, Spock provides a way to attach textual descriptions to blocks When: “everything start” • You can leverage the use of Hamcrest matchers (assertThat is aliased just as that or expect)
  • 36. Stage VI: Other mechanisms In the following spec identify with a comment which mechanisms are used (org.startrek.challenges.n06.MoviesSpec)
  • 37. No brainer (org.startrek.solutions.n06. MoviesSpec) Stage VI: Other mechanisms
  • 38. Extensions Spock offers lots of functionality for specs. But, there is always a time when something else is needed. Spock provides an interception-based extension mechanism. Extensions are activated by annotations called directives. These are some directives: • @Timeout Sets a timeout for execution of a feature or fixture • @Ignore Ignores a feature method • @IgnoreRest Ignores all feature methods not carrying this annotation • @IgnoreIf To ignore a feature method under certain conditions • @FailsWith Expects a feature method to complete abruptly • @Requires To execute a feature method under certain conditions • @Stepwise executes features in the order that they are declared • @Title and @Narrative To attach a natural-language name to a spec • @Issue indicates that a feature/spec relates to one/more issues in an external tracking system • @Subject To indicate one or more subjects of a spec • Many more! and you can also create your own ones…
  • 39. Extensions The Spock Spring extension allows Spock to integrate with Spring's TestContext framework • the extension uses Spring API • change add dependencies to our build.gradle: spock-spring, spring-context and spring-test
  • 40. Stage VI: Extensions Let’s leave that for another time… ;)
  • 41. Extra ball: Geb! Geb is a framework for automatization of functional web testing. It is based on the following technologies: • Groovy Language (and it’s incredible with Spock) • Selenium WebDriver • JQuery CSS Content Selector • Page Object Model To leveage it, we have to • change add dependencies to our build.gradle: testCompile 'org.gebish:geb-spock:0.10.0' testCompile "org.seleniumhq.selenium:selenium-chrome-driver:2.43.1” • Download and configure our driver (automated browser) in src/test/resources/GebConfig.groovy
  • 42. Create a simple driver configuration & download the driver (src/test/resources/GebConfig.groovy) Extra ball: Geb!
  • 43. Let’s perform a search for apock in memory-alpha.org (org.startrek.challenges.n07.WebNavigationSpec.groovy) Extra ball: Geb!
  • 44. That was great! But, Can YOU do it in a better way? Extra ball: Geb!
  • 45. Let’s keep it simple an reusable! Functional Spec. (org.startrek.solutions.n07.WebNavigationSpec2.groovy) Extra ball: Geb!
  • 46. Let’s keep it simple an reusable! Reusable Page Model. (org.startrek.solutions.n07. MemoryAlphaPage.groovy and org.startrek.solutions.n07. MemoryAlphaResultsPage.groovy ) Extra ball: Geb!
  • 47. And that’s it. Thanks! fredondo@pronoide.com @pronoide_fer