SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Spock
the enterprise ready specification
framework

Created by Daniel Kolman / @kolman
Spock is Groovy
...and Groovy is Bliss!

def user = new User(firstName: 'Johnny', lastName: 'Walker')
def street = company?.address?.street
users.filter { it.age > 20 }
.sort { it.salary }
.collect { it.lastName + ', ' + it.firstName }
def message = [subject: 'Hello jOpenSpace!', body: 'Meet me at the bar']

Groovy is dense and expressive. Don't
worry it's dynamic - this is a test framework
and tests are executed after every commit!
Spock Spec
def "can add an element"() {
given:
def list = new ArrayList<String>()
def element = "Hello Spock"
when:
list.add(element)
then:
list.size() == 1
list.contains(element)
}

Spock test (= "feature method") is
structured into well-known blocks
with defined meaning
Assertions
assert name.length() == 6;

expect:
name.length() == 5

java.lang.AssertionError
Condition not satisfied:
assertEquals(6, name.length());

name.length() == 5
|
|
|
Eman 4
false

// hamcrest
assertThat(name.length(), equalTo(6));
// FEST, AssertJ
assertThat(name).hasSize(6);
java.lang.AssertionError:
Expected size:<6> but was:<4> in:
<'Eman'>

Assertions commonly used in
Java are complicated or have
ugly fail messages

Spock makes it simple...
Assertions
expect:
rectangle.getArea() == a * b
Condition not satisfied:
rectangle.getArea()
|
|
|
6
Rectangle 2 x 3

== a * b
| | | |
| 4 | 5
|
20
false

…and when something goes
wrong, it writes nice and detailed
fail message
Assertions
expect:
def expectedValues =
["Legendario", "Zacapa", "Varadero", "Metusalem", "Diplomatico"]
actualValues == expectedValues
Condition not satisfied:
actualValues == expectedValues
|
| |
|
| [Legendario, Zacapa, Varadero, Metusalem, Diplomatico]
|
false
[Angostura, Legendario, Zacapa 23y, Varadero, Diplomatico]

…even for lists
IntelliJ IDEA can even display a diff of
expected and actual values
Mocking
given:
def sender = Mock(Sender)

Verifying behavior
with mock is simple

when:
println("nothing, hahaha!")
then:
1 * sender.send(_)
Too few invocations for:
1 * sender.send(_)

You can use ranges for invocation
count and wildcards for parameters

(0 invocations)

Unmatched invocations (ordered by similarity):
None
Stubbing
given:
def subscriber = Mock(Subscriber)
// pattern matching
subscriber.receive("poison") >> "oh wait..."
subscriber.receive(_) >> "ok"
when:
def response = subscriber.receive("poison")

…and setting expectations
has some powerful features

// returning sequence
subscriber.receive(_) >>> ["ok", "ok", "hey this is too much"]

// computing return value
subscriber.receive(_) >> { String msg -> msg.size() < 10 ? "ok" : "tl;dr" }
Data Driven Tests
def "maximum of two numbers"() {
expect:
Math.max(a, b) == c

def "maximum of two numbers"() {
expect:
Math.max(a, b) == expectedMax

where:
a << [1, 8, 9]
b << [7, 3, 9]
c << [7, 8, 9]

where:
a | b |
1 | 7 |
8 | 3 |
9 | 9 |

}

expectedMax
7
8
9

}

Spock has first-class
support for
parametrized tests

You can even use
table-like structure
for setting input data

Forget JUnit theories or
TestNG data providers!
QuickCheck
def "maximum of
expect:
Math.max(a,
Math.max(a,
Math.max(a,

two numbers"() {
b) == Math.max(b, a)
b) >= a && Math.max(a, b) >= b
b) == a || Math.max(a, b) == b

where:
a << someIntegers()
b << someIntegers()
}

Input data can be
anything Iterable...

…and that makes it simple to
use something like QuickCheck
for generating random data
Property-Based Testing
def "sorts a list"() {
when:
def sorted = list.sort(false)

You define invariant
"properties" that hold
true for any valid input

then:
sorted == sorted.sort(false)
sorted.first() == list.min()
sorted.last() == list.max()
sorted.eachWithIndex { x, i -> assert i==0 || sorted[i-1] <= x }
where:
list << someLists(integers())
}

Data-driven tests tend to have
different structure than traditional
"example-based" tests
I attended GOTO conference
in Amsterdam this year...
Erik Meijer
Haskell
LINQ
Rx

…and one of the speakers was Erik Meijer,
who was developing Haskell and worked on
LINQ and Reactive Extensions in Microsoft...
Machine Learning
=> { ... }

…and he gave a great talk
about machine learning
From

Subject

Spam Filter
Body

=> { ... }

In essence, machine learning is
generating computer code based
on data

E.g. generate a code to recognize
a spam, based on analysis of
bunch of email messages
Example-Based TDD
def "can detect spam"() {
expect:
spamDetector(from, subject, body) == isSpam
where:
from
'mtehnik'
'jfabian'
'jnovotny'
'katia777'

|
|
|
|
|

body
'nechces nejaky slevovy kupony na viagra?'
'mels pravdu, tu znelku cz podcastu zmenime'
'penis enlargement - great vacuum pump for you'
'we have nice russian wife for you'

||
||
||
||
||

isSpam
false
false
true
true

}

And that is very similar to TDD. You
are providing more and more test
cases to specify the desired behavior

The difference is, you don't
write the implementation - it is
generated by computer
Machine Learning
==
Automated TDD
Therefore, Erik Meijer claims
that machine learning is just
automated TDD
Prepare for the Future

In 10 years, programmers will be replaced by generated code

…and that can have some
impact on job security
Generated Code
Machine learning
Genetic programming

There are already some
real-world usages of
generated code

This is an antenna designed
by evolutionary algorithm,
that NASA actually used on
a spacecraft

http://idesign.ucsc.edu/projects/evo_antenna.html
Brain Research
Multilayer neural networks

…and our understanding of how
the brain works is getting better

https://www.simonsfoundation.org/quanta/20130723-as-machines-get-smarter-evidence-they-learn-like-us/
Property-Based Testing
def "sorts a list"() {
when:
def sorted = list.sort(false)
then:
sorted == sorted.sort(false)
sorted.first() == list.min()
sorted.last() == list.max()
sorted.eachWithIndex { x, i -> assert i==0 || sorted[i-1] <= x }
where:
list << someLists(integers())
}

Now take a second look
at property-based test

It is only matter of time when it will be
cheaper to generate code from
specification than to write it manually

Can there be better specification
for code generator?
You will be
replaced by
machine
Meanwhile, use Spock and prosper
Credits

http://www.flickr.com/photos/kt/1217157
http://www.flickr.com/photos/rooners/7290977402
http://www.flickr.com/photos/jdhancock/4425900247
http://www.agiledojo.net/2013/09/and-now-for-somethingcompletely.html
https://www.simonsfoundation.org/quanta/20130723-asmachines-get-smarter-evidence-they-learn-like-us/
TestNG vs. Spock
@DataProvider(name = "maximumOfTwoNumbersProvider")
public Object[][] createDataForMaximum() {
return new Object[][]{
{1, 7, 7},
{8, 3, 8},
{9, 9, 9}
};
}
@Test(dataProvider = "maximumOfTwoNumbersProvider")
public void maximumOfTwoNumbers(int a, int b, int expectedMax) {
assertThat(Math.max(a, b)).isEqualTo(expectedMax);
}

def "maximum of two numbers"() {
expect:
Math.max(a, b) == expectedMax
where:
a | b |
1 | 7 |
8 | 3 |
9 | 9 |
}

expectedMax
7
8
9

Bonus slide - comparison of
parametrized test in TestNG
(above) and Spock (bellow)

Weitere ähnliche Inhalte

Was ist angesagt?

JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainersSunghyouk Bae
 
An Introduction to CMake
An Introduction to CMakeAn Introduction to CMake
An Introduction to CMakeICS
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldYura Nosenko
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesGanesh Samarthyam
 
Dvwa low level
Dvwa low levelDvwa low level
Dvwa low levelhackstuff
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring SecurityDzmitry Naskou
 
Docker Concepts for Oracle/MySQL DBAs and DevOps
Docker Concepts for Oracle/MySQL DBAs and DevOpsDocker Concepts for Oracle/MySQL DBAs and DevOps
Docker Concepts for Oracle/MySQL DBAs and DevOpsZohar Elkayam
 
An introduction to maven gradle and sbt
An introduction to maven gradle and sbtAn introduction to maven gradle and sbt
An introduction to maven gradle and sbtFabio Fumarola
 
Apache Wicketのユニットテスト機能
Apache Wicketのユニットテスト機能Apache Wicketのユニットテスト機能
Apache Wicketのユニットテスト機能Hiroto Yamakawa
 
Asm bot mitigations v3 final- lior rotkovitch
Asm bot mitigations v3 final- lior rotkovitchAsm bot mitigations v3 final- lior rotkovitch
Asm bot mitigations v3 final- lior rotkovitchLior Rotkovitch
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions WebStackAcademy
 
Tester unitairement une application java
Tester unitairement une application javaTester unitairement une application java
Tester unitairement une application javaAntoine Rey
 
JavaScriptの落とし穴
JavaScriptの落とし穴JavaScriptの落とし穴
JavaScriptの落とし穴ikdysfm
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introductionDenis Bazhin
 

Was ist angesagt? (20)

JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
TestNG
TestNGTestNG
TestNG
 
An Introduction to CMake
An Introduction to CMakeAn Introduction to CMake
An Introduction to CMake
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 world
 
Soap ui
Soap uiSoap ui
Soap ui
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Junit
JunitJunit
Junit
 
Dvwa low level
Dvwa low levelDvwa low level
Dvwa low level
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 
Docker Concepts for Oracle/MySQL DBAs and DevOps
Docker Concepts for Oracle/MySQL DBAs and DevOpsDocker Concepts for Oracle/MySQL DBAs and DevOps
Docker Concepts for Oracle/MySQL DBAs and DevOps
 
An introduction to maven gradle and sbt
An introduction to maven gradle and sbtAn introduction to maven gradle and sbt
An introduction to maven gradle and sbt
 
Apache Wicketのユニットテスト機能
Apache Wicketのユニットテスト機能Apache Wicketのユニットテスト機能
Apache Wicketのユニットテスト機能
 
Asm bot mitigations v3 final- lior rotkovitch
Asm bot mitigations v3 final- lior rotkovitchAsm bot mitigations v3 final- lior rotkovitch
Asm bot mitigations v3 final- lior rotkovitch
 
JDBC
JDBCJDBC
JDBC
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Tester unitairement une application java
Tester unitairement une application javaTester unitairement une application java
Tester unitairement une application java
 
JavaScriptの落とし穴
JavaScriptの落とし穴JavaScriptの落とし穴
JavaScriptの落とし穴
 
Python unit testing
Python unit testingPython unit testing
Python unit testing
 
Log4 J
Log4 JLog4 J
Log4 J
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 

Andere mochten auch

Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with SpockDmitry Voloshko
 
Spock Framework 2
Spock Framework 2Spock Framework 2
Spock Framework 2Ismael
 
Groovier testing with Spock
Groovier testing with SpockGroovier testing with Spock
Groovier testing with SpockRobert Fletcher
 
VirtualJUG24 - Testing with Spock: The logical choice
VirtualJUG24 - Testing with Spock: The logical choiceVirtualJUG24 - Testing with Spock: The logical choice
VirtualJUG24 - Testing with Spock: The logical choiceIván López Martín
 
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...Iván López Martín
 
Testing Storm components with Groovy and Spock
Testing Storm components with Groovy and SpockTesting Storm components with Groovy and Spock
Testing Storm components with Groovy and SpockEugene Dvorkin
 
A Gentle Introduction To Docker And All Things Containers
A Gentle Introduction To Docker And All Things ContainersA Gentle Introduction To Docker And All Things Containers
A Gentle Introduction To Docker And All Things ContainersJérôme Petazzoni
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesNed Potter
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017Drift
 

Andere mochten auch (14)

Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with Spock
 
Spock Framework 2
Spock Framework 2Spock Framework 2
Spock Framework 2
 
Groovier testing with Spock
Groovier testing with SpockGroovier testing with Spock
Groovier testing with Spock
 
VirtualJUG24 - Testing with Spock: The logical choice
VirtualJUG24 - Testing with Spock: The logical choiceVirtualJUG24 - Testing with Spock: The logical choice
VirtualJUG24 - Testing with Spock: The logical choice
 
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
 
Testing Storm components with Groovy and Spock
Testing Storm components with Groovy and SpockTesting Storm components with Groovy and Spock
Testing Storm components with Groovy and Spock
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
Spock
SpockSpock
Spock
 
Geb with spock
Geb with spockGeb with spock
Geb with spock
 
A Gentle Introduction To Docker And All Things Containers
A Gentle Introduction To Docker And All Things ContainersA Gentle Introduction To Docker And All Things Containers
A Gentle Introduction To Docker And All Things Containers
 
Docker by Example - Basics
Docker by Example - Basics Docker by Example - Basics
Docker by Example - Basics
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and Archives
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017
 

Ähnlich wie Spock Framework

BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebChristian Baranowski
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and ProsperKen Kousen
 
Build a Complex, Realtime Data Management App with Postgres 14!
Build a Complex, Realtime Data Management App with Postgres 14!Build a Complex, Realtime Data Management App with Postgres 14!
Build a Complex, Realtime Data Management App with Postgres 14!Jonathan Katz
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages VictorSzoltysek
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
DEF CON 23 - amit ashbel and maty siman - game of hacks
DEF CON 23 - amit ashbel and maty siman - game of hacks DEF CON 23 - amit ashbel and maty siman - game of hacks
DEF CON 23 - amit ashbel and maty siman - game of hacks Felipe Prado
 
Viktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning ServiceViktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning ServiceLviv Startup Club
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot CampTroy Miles
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
Visual diagnostics at scale
Visual diagnostics at scaleVisual diagnostics at scale
Visual diagnostics at scaleRebecca Bilbro
 
Image classification using cnn
Image classification using cnnImage classification using cnn
Image classification using cnnDebarko De
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - StockholmJan Kronquist
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Yevgeniy Brikman
 
Pocket Talk; Spock framework
Pocket Talk; Spock frameworkPocket Talk; Spock framework
Pocket Talk; Spock frameworkInfoway
 

Ähnlich wie Spock Framework (20)

Spock
SpockSpock
Spock
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
Build a Complex, Realtime Data Management App with Postgres 14!
Build a Complex, Realtime Data Management App with Postgres 14!Build a Complex, Realtime Data Management App with Postgres 14!
Build a Complex, Realtime Data Management App with Postgres 14!
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
DEF CON 23 - amit ashbel and maty siman - game of hacks
DEF CON 23 - amit ashbel and maty siman - game of hacks DEF CON 23 - amit ashbel and maty siman - game of hacks
DEF CON 23 - amit ashbel and maty siman - game of hacks
 
Viktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning ServiceViktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning Service
 
Spock and Geb in Action
Spock and Geb in ActionSpock and Geb in Action
Spock and Geb in Action
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
Visual diagnostics at scale
Visual diagnostics at scaleVisual diagnostics at scale
Visual diagnostics at scale
 
Image classification using cnn
Image classification using cnnImage classification using cnn
Image classification using cnn
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Go testdeep
Go testdeepGo testdeep
Go testdeep
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
 
Pocket Talk; Spock framework
Pocket Talk; Spock frameworkPocket Talk; Spock framework
Pocket Talk; Spock framework
 

Kürzlich hochgeladen

So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
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
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Nikki Chapple
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...amber724300
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 

Kürzlich hochgeladen (20)

So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
How Tech Giants Cut Corners to Harvest Data for A.I.
How Tech Giants Cut Corners to Harvest Data for A.I.How Tech Giants Cut Corners to Harvest Data for A.I.
How Tech Giants Cut Corners to Harvest Data for A.I.
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
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
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 

Spock Framework

  • 1. Spock the enterprise ready specification framework Created by Daniel Kolman / @kolman
  • 2. Spock is Groovy ...and Groovy is Bliss! def user = new User(firstName: 'Johnny', lastName: 'Walker') def street = company?.address?.street users.filter { it.age > 20 } .sort { it.salary } .collect { it.lastName + ', ' + it.firstName } def message = [subject: 'Hello jOpenSpace!', body: 'Meet me at the bar'] Groovy is dense and expressive. Don't worry it's dynamic - this is a test framework and tests are executed after every commit!
  • 3. Spock Spec def "can add an element"() { given: def list = new ArrayList<String>() def element = "Hello Spock" when: list.add(element) then: list.size() == 1 list.contains(element) } Spock test (= "feature method") is structured into well-known blocks with defined meaning
  • 4. Assertions assert name.length() == 6; expect: name.length() == 5 java.lang.AssertionError Condition not satisfied: assertEquals(6, name.length()); name.length() == 5 | | | Eman 4 false // hamcrest assertThat(name.length(), equalTo(6)); // FEST, AssertJ assertThat(name).hasSize(6); java.lang.AssertionError: Expected size:<6> but was:<4> in: <'Eman'> Assertions commonly used in Java are complicated or have ugly fail messages Spock makes it simple...
  • 5. Assertions expect: rectangle.getArea() == a * b Condition not satisfied: rectangle.getArea() | | | 6 Rectangle 2 x 3 == a * b | | | | | 4 | 5 | 20 false …and when something goes wrong, it writes nice and detailed fail message
  • 6. Assertions expect: def expectedValues = ["Legendario", "Zacapa", "Varadero", "Metusalem", "Diplomatico"] actualValues == expectedValues Condition not satisfied: actualValues == expectedValues | | | | | [Legendario, Zacapa, Varadero, Metusalem, Diplomatico] | false [Angostura, Legendario, Zacapa 23y, Varadero, Diplomatico] …even for lists
  • 7. IntelliJ IDEA can even display a diff of expected and actual values
  • 8. Mocking given: def sender = Mock(Sender) Verifying behavior with mock is simple when: println("nothing, hahaha!") then: 1 * sender.send(_) Too few invocations for: 1 * sender.send(_) You can use ranges for invocation count and wildcards for parameters (0 invocations) Unmatched invocations (ordered by similarity): None
  • 9. Stubbing given: def subscriber = Mock(Subscriber) // pattern matching subscriber.receive("poison") >> "oh wait..." subscriber.receive(_) >> "ok" when: def response = subscriber.receive("poison") …and setting expectations has some powerful features // returning sequence subscriber.receive(_) >>> ["ok", "ok", "hey this is too much"] // computing return value subscriber.receive(_) >> { String msg -> msg.size() < 10 ? "ok" : "tl;dr" }
  • 10. Data Driven Tests def "maximum of two numbers"() { expect: Math.max(a, b) == c def "maximum of two numbers"() { expect: Math.max(a, b) == expectedMax where: a << [1, 8, 9] b << [7, 3, 9] c << [7, 8, 9] where: a | b | 1 | 7 | 8 | 3 | 9 | 9 | } expectedMax 7 8 9 } Spock has first-class support for parametrized tests You can even use table-like structure for setting input data Forget JUnit theories or TestNG data providers!
  • 11. QuickCheck def "maximum of expect: Math.max(a, Math.max(a, Math.max(a, two numbers"() { b) == Math.max(b, a) b) >= a && Math.max(a, b) >= b b) == a || Math.max(a, b) == b where: a << someIntegers() b << someIntegers() } Input data can be anything Iterable... …and that makes it simple to use something like QuickCheck for generating random data
  • 12. Property-Based Testing def "sorts a list"() { when: def sorted = list.sort(false) You define invariant "properties" that hold true for any valid input then: sorted == sorted.sort(false) sorted.first() == list.min() sorted.last() == list.max() sorted.eachWithIndex { x, i -> assert i==0 || sorted[i-1] <= x } where: list << someLists(integers()) } Data-driven tests tend to have different structure than traditional "example-based" tests
  • 13.
  • 14. I attended GOTO conference in Amsterdam this year...
  • 15. Erik Meijer Haskell LINQ Rx …and one of the speakers was Erik Meijer, who was developing Haskell and worked on LINQ and Reactive Extensions in Microsoft...
  • 16. Machine Learning => { ... } …and he gave a great talk about machine learning
  • 17. From Subject Spam Filter Body => { ... } In essence, machine learning is generating computer code based on data E.g. generate a code to recognize a spam, based on analysis of bunch of email messages
  • 18. Example-Based TDD def "can detect spam"() { expect: spamDetector(from, subject, body) == isSpam where: from 'mtehnik' 'jfabian' 'jnovotny' 'katia777' | | | | | body 'nechces nejaky slevovy kupony na viagra?' 'mels pravdu, tu znelku cz podcastu zmenime' 'penis enlargement - great vacuum pump for you' 'we have nice russian wife for you' || || || || || isSpam false false true true } And that is very similar to TDD. You are providing more and more test cases to specify the desired behavior The difference is, you don't write the implementation - it is generated by computer
  • 19. Machine Learning == Automated TDD Therefore, Erik Meijer claims that machine learning is just automated TDD
  • 20. Prepare for the Future In 10 years, programmers will be replaced by generated code …and that can have some impact on job security
  • 21. Generated Code Machine learning Genetic programming There are already some real-world usages of generated code This is an antenna designed by evolutionary algorithm, that NASA actually used on a spacecraft http://idesign.ucsc.edu/projects/evo_antenna.html
  • 22. Brain Research Multilayer neural networks …and our understanding of how the brain works is getting better https://www.simonsfoundation.org/quanta/20130723-as-machines-get-smarter-evidence-they-learn-like-us/
  • 23. Property-Based Testing def "sorts a list"() { when: def sorted = list.sort(false) then: sorted == sorted.sort(false) sorted.first() == list.min() sorted.last() == list.max() sorted.eachWithIndex { x, i -> assert i==0 || sorted[i-1] <= x } where: list << someLists(integers()) } Now take a second look at property-based test It is only matter of time when it will be cheaper to generate code from specification than to write it manually Can there be better specification for code generator?
  • 24. You will be replaced by machine Meanwhile, use Spock and prosper
  • 26. TestNG vs. Spock @DataProvider(name = "maximumOfTwoNumbersProvider") public Object[][] createDataForMaximum() { return new Object[][]{ {1, 7, 7}, {8, 3, 8}, {9, 9, 9} }; } @Test(dataProvider = "maximumOfTwoNumbersProvider") public void maximumOfTwoNumbers(int a, int b, int expectedMax) { assertThat(Math.max(a, b)).isEqualTo(expectedMax); } def "maximum of two numbers"() { expect: Math.max(a, b) == expectedMax where: a | b | 1 | 7 | 8 | 3 | 9 | 9 | } expectedMax 7 8 9 Bonus slide - comparison of parametrized test in TestNG (above) and Spock (bellow)