SlideShare a Scribd company logo
1 of 29
Unit Testing using Spock
Presented By: Anuj Aneja
What is unit testing?
 A unit is the smallest testable part of an application like
functions, classes, procedures, interfaces. Unit testing is
a method by which individual units of source code are
tested to determine if they are fit for use.
 Unit tests are basically written and executed by software
developers to make sure that code meets its design and
requirements and behaves as expected
 The goal of unit testing is to segregate each part of the
program and test that the individual parts are working
correctly.
 This means that for any function or procedure when a
set of inputs are given then it should return the proper
values. It should handle the failures gracefully during
the course of execution when any invalid input is given.
What is unit testing?…..continued
 A unit test provides a written contract that the piece of
code must assure. Hence it has several benefits.
 Unit testing is usually done before integration testing.
Do we need to test the code
before we build it?
Advantages of Unit Testing
 Issues are found at early stage. Since unit testing are
carried out by developers where they test their
individual code before the integration.
 Unit testing helps in maintaining and changing the code.
This is possible by making the codes less interdependent
so that unit testing can be executed.
 Unit testing helps in simplifying the debugging process.
If suppose a test fails then only latest changes made in
code needs to be debugged.
Unit testing using Spock
 What is Spock?
 Why Spock?
 Example
 Test Structure
 Creating Mock
 Checking interactions with Mock object
 Matching invocations in mocks
Unit testing using spock
 Check the order of execution
 Specifying a cardinality of an interaction &
wildcards
 Managing exceptions in tests
 Shared variables
 “>>” operator & Stubbing
 Good practices
What is Spock?
 Spock is a unit testing framework that in great extent
utilizes Groovy’s syntax making your tests
comprehensible and easy on the eyes. Although it is a
Groovy technology you can use it to test your Java
classes as well. What is the most important is
that Spock makes writing tests fun. And I really
mean it.
Why Spock?
 Creating a test in Spock takes less time than using its
standard equivalent (combination of JUnit and some
mocking framework)
 Thanks to Groovy’s syntax you can improve tests
clarity even further using closures and straightforward
map ulization.
Example
def "should return 2 from first element of list"() {
given:
List<Integer> list = new ArrayList<>()
when:
list.add(1)
then:
2 == list.get(0)
}
Output: Error Message
Condition not satisfied:
2 == list.get(0)
| | |
| [1] 1
false
Test Structure
 Each test can be divided into three sections
 Given
 When
 Then
 Alternative Sections:
 Setup
 expect
Mandatory Sections Example
def "should return false if user does not have
role required for viewing page"() {
given:
// context within which you want to test the
functionality.
pageRequiresRole Role.ADMIN
userHasRole Role.USER
when:
// some action is performed i.e. actual
method call
boolean authorized =
authorizationService.isUserAuthorizedForPage(u
ser, page)
then:
// expect specific result
authorized == false
}
Alternative Sections:
setup,expect
 An expect block is more limited than a then block in that
it 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. For example, compare the following two
attempts to describe the Math.max() method:
when: def x = Math.max(1, 2)
then: x == 2
expect: Math.max(1, 2) == 2
Flow
Creating Mock
In order to create a Mock one has to call Mock() method
inside a Spock test.
e.g.
def "creating example mocks"() {
given:
List list = Mock(List)
List list2 = Mock() // preffered way
def list3 = Mock(List)
}
Checking interactions with
Mock object
Now that we have created a Mock object, we can check
what has happened with the object during the execution of
code inside when section.
def "size method should be executed one time"() {
given:
List list
when:
list = Mock()
then:
1 * list.size()
}
Output
Error Message:
Too few invocations for:
1 * list.size() (0 invocations)
Unmatched invocations (ordered by similarity):
None
Matching invocations in
mocks
def "should fail due to wrong user"() {
given:
UserService userService = Mock()
User user = new User(name: 'Mefisto')
when:
userService.save(user)
then:
1 * userService.save({ User u -> u.name == 'Lucas' })
}
Too few invocations for:
1 * userService.save({ User u -> u.name == 'Lucas' }) (0
invocations)
Check the order of execution
What is more you can even specify the order by which
interactions should take place. This is achieved by
creating numerous thensections.
def "should first save object before committing
transaction"() {
given:
UserService service = Mock()
Transaction transaction = Mock()
when:
service.save(new User())
transaction.commit()
then:
1 * service.save(_ as User)
then:
1 * transaction.commit()
}
Specifying a cardinality of an
interaction & wildcards
then:
// should not be invoked at all
0 * list.size()
// should be invoked at least one time
(1.._) * list.size()
// should be invoked at most one time
(_..1) * list.size()
// any number of calls
_ * list.size()
Managing exceptions in tests
There are special method for handling exception
checking
Thrown(), notThrown(), noExceptionThrown()
e.g.
def "should throw IllegalArgumentException with
proper message"() {
when:
throw new IllegalArgumentException("Does
description matter?")
then:
def e = thrown(IllegalArgumentException)
e.message == "Does description matter?"
}
Shared variables
If for some reason you would prefer to share the
state of objects created at the level class you
can annotate this particular variable
with @Shared annotation.
@Shared
private List<Integer> list = []
def "test 1"() {
when:
list.add(1)
then:
list.size() == 1
}
def "test 2"() {
when:
list.add(1)
“>>” operator & stubbing
Stubbing is the act of making collaborators respond to method calls
in a certain way. When stubbing a method, you don’t care if and
how many times the method is going to be called; you just want it
to return some value, or perform some side effect, whenever it gets
called.
For Example:
interface Subscriber {
String receive(String message)
}
Now, let’s make the receive method return "ok" on every
invocation:
subscriber.receive(_) >> "ok"
"Whenever the subscriber receives a message, make it respond with
'ok'."
Compared to a mocked interaction, a stubbed interaction has no
cardinality on the left end, but adds a response generator on the
right end:
subscriber.receive(_) >> "ok"
| | | |
| | | response generator
| | argument constraint
| method constraint
target constraint
Good practicies:
 Using descriptive methods inside test
 Removing disruptive code
Removing disruptive code
private User user
private Action action
private TicketOrder order
private BookingService objectUnderTest = new
BookingService()
def "should throw exception if user tries to cancel tickets to
a gig that starts in less than two days"() {
given:
userHasRoleUser()
cancelActionOn10thOfDec2000()
showIsGigThatStartsOn11thOfDec2000()
when:
objectUnderTest.book(user, order, action)
then:
thrown(IllegalActionException)
}
Q & A

More Related Content

What's hot

Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfixSelf-Employed
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and AlgorithmDhaval Kaneria
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTSoumen Santra
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesFahim Ferdous
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysMartin Chapman
 
minimum spanning trees Algorithm
minimum spanning trees Algorithm minimum spanning trees Algorithm
minimum spanning trees Algorithm sachin varun
 
Presentation on array
Presentation on array Presentation on array
Presentation on array topu93
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2Rajendran
 
Stack - Data Structure - Notes
Stack - Data Structure - NotesStack - Data Structure - Notes
Stack - Data Structure - NotesOmprakash Chauhan
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)PyData
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHPRamasubbu .P
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 

What's hot (20)

Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfix
 
JavaFX Presentation
JavaFX PresentationJavaFX Presentation
JavaFX Presentation
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
 
N queen problem
N queen problemN queen problem
N queen problem
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and Examples
 
Array in c
Array in cArray in c
Array in c
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Python basics
Python basicsPython basics
Python basics
 
minimum spanning trees Algorithm
minimum spanning trees Algorithm minimum spanning trees Algorithm
minimum spanning trees Algorithm
 
Arrays
ArraysArrays
Arrays
 
Presentation on array
Presentation on array Presentation on array
Presentation on array
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2
 
Stack - Data Structure - Notes
Stack - Data Structure - NotesStack - Data Structure - Notes
Stack - Data Structure - Notes
 
Strings and pointers
Strings and pointersStrings and pointers
Strings and pointers
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Tower of hanoi
Tower of hanoiTower of hanoi
Tower of hanoi
 
C# Basics
C# BasicsC# Basics
C# Basics
 

Viewers also liked

Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with SpockDmitry Voloshko
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With SpockIT Weekend
 
Vert.x 세미나 이지원_배포용
Vert.x 세미나 이지원_배포용Vert.x 세미나 이지원_배포용
Vert.x 세미나 이지원_배포용지원 이
 
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
 

Viewers also liked (7)

Spock
SpockSpock
Spock
 
Spring puzzlers
Spring puzzlersSpring puzzlers
Spring puzzlers
 
Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with Spock
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
Vert.x 세미나 이지원_배포용
Vert.x 세미나 이지원_배포용Vert.x 세미나 이지원_배포용
Vert.x 세미나 이지원_배포용
 
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)
 

Similar to Unit/Integration Testing using Spock

Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittestFariz Darari
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Fariz Darari
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingAnna Khabibullina
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnitAktuğ Urun
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock TutorialSbin m
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocksguillaumecarre
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and ProsperKen Kousen
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lispelliando dias
 
Using Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingUsing Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingMike Clement
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseUTC Fire & Security
 
Test Driven Development - The art of fearless programming
Test Driven Development - The art of fearless programmingTest Driven Development - The art of fearless programming
Test Driven Development - The art of fearless programmingChamil Jeewantha
 
Software Testing for Data Scientists
Software Testing for Data ScientistsSoftware Testing for Data Scientists
Software Testing for Data ScientistsAjay Ohri
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialAnup Singh
 
CS5393-Korat_Mittal_Akshay_ProjReport
CS5393-Korat_Mittal_Akshay_ProjReportCS5393-Korat_Mittal_Akshay_ProjReport
CS5393-Korat_Mittal_Akshay_ProjReportAkshay Mittal
 
Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminardunglinh111
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 

Similar to Unit/Integration Testing using Spock (20)

Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittest
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)
 
Unit testing
Unit testingUnit testing
Unit testing
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testing
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
Rspec
RspecRspec
Rspec
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocks
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
 
Using Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingUsing Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit Testing
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Test Driven Development - The art of fearless programming
Test Driven Development - The art of fearless programmingTest Driven Development - The art of fearless programming
Test Driven Development - The art of fearless programming
 
Software Testing for Data Scientists
Software Testing for Data ScientistsSoftware Testing for Data Scientists
Software Testing for Data Scientists
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
CS5393-Korat_Mittal_Akshay_ProjReport
CS5393-Korat_Mittal_Akshay_ProjReportCS5393-Korat_Mittal_Akshay_ProjReport
CS5393-Korat_Mittal_Akshay_ProjReport
 
Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminar
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 

Recently uploaded

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Recently uploaded (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

Unit/Integration Testing using Spock

  • 1. Unit Testing using Spock Presented By: Anuj Aneja
  • 2. What is unit testing?  A unit is the smallest testable part of an application like functions, classes, procedures, interfaces. Unit testing is a method by which individual units of source code are tested to determine if they are fit for use.  Unit tests are basically written and executed by software developers to make sure that code meets its design and requirements and behaves as expected  The goal of unit testing is to segregate each part of the program and test that the individual parts are working correctly.  This means that for any function or procedure when a set of inputs are given then it should return the proper values. It should handle the failures gracefully during the course of execution when any invalid input is given.
  • 3. What is unit testing?…..continued  A unit test provides a written contract that the piece of code must assure. Hence it has several benefits.  Unit testing is usually done before integration testing.
  • 4. Do we need to test the code before we build it?
  • 5.
  • 6. Advantages of Unit Testing  Issues are found at early stage. Since unit testing are carried out by developers where they test their individual code before the integration.  Unit testing helps in maintaining and changing the code. This is possible by making the codes less interdependent so that unit testing can be executed.  Unit testing helps in simplifying the debugging process. If suppose a test fails then only latest changes made in code needs to be debugged.
  • 7. Unit testing using Spock  What is Spock?  Why Spock?  Example  Test Structure  Creating Mock  Checking interactions with Mock object  Matching invocations in mocks
  • 8. Unit testing using spock  Check the order of execution  Specifying a cardinality of an interaction & wildcards  Managing exceptions in tests  Shared variables  “>>” operator & Stubbing  Good practices
  • 9. What is Spock?  Spock is a unit testing framework that in great extent utilizes Groovy’s syntax making your tests comprehensible and easy on the eyes. Although it is a Groovy technology you can use it to test your Java classes as well. What is the most important is that Spock makes writing tests fun. And I really mean it.
  • 10. Why Spock?  Creating a test in Spock takes less time than using its standard equivalent (combination of JUnit and some mocking framework)  Thanks to Groovy’s syntax you can improve tests clarity even further using closures and straightforward map ulization.
  • 11. Example def "should return 2 from first element of list"() { given: List<Integer> list = new ArrayList<>() when: list.add(1) then: 2 == list.get(0) }
  • 12. Output: Error Message Condition not satisfied: 2 == list.get(0) | | | | [1] 1 false
  • 13. Test Structure  Each test can be divided into three sections  Given  When  Then  Alternative Sections:  Setup  expect
  • 14. Mandatory Sections Example def "should return false if user does not have role required for viewing page"() { given: // context within which you want to test the functionality. pageRequiresRole Role.ADMIN userHasRole Role.USER when: // some action is performed i.e. actual method call boolean authorized = authorizationService.isUserAuthorizedForPage(u ser, page) then: // expect specific result authorized == false }
  • 15. Alternative Sections: setup,expect  An expect block is more limited than a then block in that it 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. For example, compare the following two attempts to describe the Math.max() method: when: def x = Math.max(1, 2) then: x == 2 expect: Math.max(1, 2) == 2
  • 16. Flow
  • 17. Creating Mock In order to create a Mock one has to call Mock() method inside a Spock test. e.g. def "creating example mocks"() { given: List list = Mock(List) List list2 = Mock() // preffered way def list3 = Mock(List) }
  • 18. Checking interactions with Mock object Now that we have created a Mock object, we can check what has happened with the object during the execution of code inside when section. def "size method should be executed one time"() { given: List list when: list = Mock() then: 1 * list.size() }
  • 19. Output Error Message: Too few invocations for: 1 * list.size() (0 invocations) Unmatched invocations (ordered by similarity): None
  • 20. Matching invocations in mocks def "should fail due to wrong user"() { given: UserService userService = Mock() User user = new User(name: 'Mefisto') when: userService.save(user) then: 1 * userService.save({ User u -> u.name == 'Lucas' }) } Too few invocations for: 1 * userService.save({ User u -> u.name == 'Lucas' }) (0 invocations)
  • 21. Check the order of execution What is more you can even specify the order by which interactions should take place. This is achieved by creating numerous thensections. def "should first save object before committing transaction"() { given: UserService service = Mock() Transaction transaction = Mock() when: service.save(new User()) transaction.commit() then: 1 * service.save(_ as User) then: 1 * transaction.commit() }
  • 22. Specifying a cardinality of an interaction & wildcards then: // should not be invoked at all 0 * list.size() // should be invoked at least one time (1.._) * list.size() // should be invoked at most one time (_..1) * list.size() // any number of calls _ * list.size()
  • 23. Managing exceptions in tests There are special method for handling exception checking Thrown(), notThrown(), noExceptionThrown() e.g. def "should throw IllegalArgumentException with proper message"() { when: throw new IllegalArgumentException("Does description matter?") then: def e = thrown(IllegalArgumentException) e.message == "Does description matter?" }
  • 24. Shared variables If for some reason you would prefer to share the state of objects created at the level class you can annotate this particular variable with @Shared annotation. @Shared private List<Integer> list = [] def "test 1"() { when: list.add(1) then: list.size() == 1 } def "test 2"() { when: list.add(1)
  • 25. “>>” operator & stubbing Stubbing is the act of making collaborators respond to method calls in a certain way. When stubbing a method, you don’t care if and how many times the method is going to be called; you just want it to return some value, or perform some side effect, whenever it gets called. For Example: interface Subscriber { String receive(String message) } Now, let’s make the receive method return "ok" on every invocation: subscriber.receive(_) >> "ok"
  • 26. "Whenever the subscriber receives a message, make it respond with 'ok'." Compared to a mocked interaction, a stubbed interaction has no cardinality on the left end, but adds a response generator on the right end: subscriber.receive(_) >> "ok" | | | | | | | response generator | | argument constraint | method constraint target constraint
  • 27. Good practicies:  Using descriptive methods inside test  Removing disruptive code
  • 28. Removing disruptive code private User user private Action action private TicketOrder order private BookingService objectUnderTest = new BookingService() def "should throw exception if user tries to cancel tickets to a gig that starts in less than two days"() { given: userHasRoleUser() cancelActionOn10thOfDec2000() showIsGigThatStartsOn11thOfDec2000() when: objectUnderTest.book(user, order, action) then: thrown(IllegalActionException) }
  • 29. Q & A